VladRia VladRia - 3 months ago 14
AngularJS Question

filter of related selects in ng-options

I have two (three)

select
tags that list the same options (brans). I would like to prevent user of choosing the same values in these selects.

controller:

$scope.brands = [
{id: '1', name: 'Peugeot'},
{id: '2', name:'BMW'},
{id: '3', name:'Mercedes'}
];


In template I tried to use
filter
filter in two ways:

<body ng-controller="FilterCtrl">
<div>
<select ng-model="conf.brand1" ng-options="b.id as b.name for b in brands"></select>
</div>

<div>
<select ng-model="conf.brand2"
ng-options="b.id as b.name for b in brands | filter : !conf.brand1 : true"></select>
</div>

<div>
<select ng-model="conf.brand2"
ng-options="b.id as b.name for b in brands | filter : conf.brand1 : compareBrands"></select>
</div>
</body>


with
compareBrands
function:

$scope.compareBrands = function(id, already_selected) {
return id != already_selected;
}


none of this is working. Here is a plunker of my problem.

Thank you.

Answer

The possible way is to use compareBrands function as expression, to do so, change your third filter to:

<select ng-model="conf.brand2" 
          ng-options="b.id as b.name for b in brands | filter : compareBrands"></select>

And compareBrand function to:

$scope.compareBrands = function(obj) {
  return obj.id !== $scope.conf.brand1;
}

See modified plunker.

EDIT: I would like to point out that value of conf.brand1 will be it's id so if you still ok with that and don't want create comparator function for each select you should use this form instead:

      <select ng-model="conf.brand2" 
          ng-options="b.id as b.name for b in brands | filter : {id: (conf.brand1 ? ('!' + conf.brand1) : '')}"></select>
Comments