Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out values dynamically from a select using angular js

I have a select where I am populating certain values as below:

The values are:

     $scope.obj = {codes: [
        {code: 1},
        {code: 2},
        {code: 3}
     ]};

Now I want to filter certain values dynamically without making any changes in the $scope.obj value i.e. I don't want to display the {code:1} value. I have set this value in another $scope variable:

$scope.selectedCode = {code:1};

Whatever values is present in selected code should not be displayed in the select drop down. I think this can be done using angular js filter expression:

<select ng-options="c.code for c in obj.codes | filter:'c.code !== selectedCode .code'" ng-model="selected">

But the above is displaying an empty drop down.

Any help/guidance is most welcome.Thanks in advance. :)

like image 527
Jyotirmoy Pan Avatar asked Mar 18 '23 11:03

Jyotirmoy Pan


1 Answers

Create helper method in controller:

$scope.filterCodes = function(obj) {
    return obj.code !== $scope.selectedCode.code;
};

and use it as custom filter:

<select ng-options="c.code for c in obj.codes | filter:filterCodes" ng-model="selected"></select>

UPD. There is also pure template solution without controller function:

ng-options="c.code for c in obj.codes | filter: '!' + selectedCode.code"
like image 175
dfsq Avatar answered Apr 25 '23 07:04

dfsq