1

I Have a problem with filter in AngularJS . i use filter to show options based Input From Search Box . everything works but every time i search(except default option (Set with ng-model)) it adds a null option in results .

i set ng-model for <select> tag

here is my Code

<div class="choosePatternHeader">
    <span>Pattern name</span>
    <input ng-model="obj.name" type="text">

</div>
<div class="select_div">
    <select  size="4"  ng-model="pattern" ng-options="p.name  for p in patterns | filter:obj">
    </select>
</div>

here is result when i search "pattern 4"

<select class="ng-pristine ng-valid" ng-options="p.name for p in patterns | filter:obj"    ng-model="pattern" size="4">
<option value="?" selected="selected"></option>
<option value="0">pattern 4</option>
</select>

and result when i search "pattern 1" (default option)

 <select class="ng-pristine ng-valid" ng-options="p.name for p in patterns | filter:obj"    ng-model="pattern" size="4">
<option value="0">pattern 1</option>
</select>

here is a jsFiddle

3 Answers 3

1

The same happens with <option ng-repeat="p in patterns">, so I guess that's the underlying problem.

The only "solution" I have found is to simply make use of the empty value by defining an empty option, e.g. <option value="">Please select</option>.

Sign up to request clarification or add additional context in comments.

1 Comment

tnx you . i have created an issue on Git of AngularJS
1

I solved as follows

function MyController($scope, $filter)
{
    $scope.patterns=[{name:'pattern 1'},{name:'pattern 2'},{name:'pattern 3'},{name:'pattern 4'}];
    $scope.pattern=$scope.patterns[0];

    $scope.$watch('obj.name', function(value){
          var filtered_devices = $filter('filter')($scope.patterns, {name:$scope.obj.name});         
          if (filtered_devices) {
              $scope.pattern = filtered_devices[0];
          }
    }, true);
}

Comments

0

AngularJS will indeed add a dummy option if ng-model is set to a value that is not in ng-options. I am not aware of a way to prevent this when the filter doesn't return any values (when ng-options is empty, ng-model can never be in it), but when it does, you could set ng-model to the first item, which means the dummy option will not be created. You could use ng-change or similar to do this.

1 Comment

i add ng-model . try my jsFiddle link . everything work untill when i insert a string in searchbox to filter the data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.