user1264595
user1264595

Reputation: 3

AngularJS filter already selected options

I have 3 selects that all share the same options. As an option is selected in one of them, I want to filter it out of the other selects.

I took a stab at it here and did not have any luck. http://plnkr.co/edit/ERGTbQSjoX3IpGAomcUn?p=preview

<select name="ques1" ng-model="q1" required>
    <option value="">question</option>
    <option ng-repeat="question in questions | filter: { Id : '!' + q2 } | filter: { Id : '!' + q3 }" value="{{ question.Id }}">{{ question.Question }}</option>
</select>

Any advice? And thanks in advance.

Upvotes: 0

Views: 622

Answers (2)

Qi Tang
Qi Tang

Reputation: 1165

I finally make it work. According to the document. You can pass a function as argument to the filter. So I created a function that returns a function which will be passed to filter:

  $scope.negative = function(){
    var arr = Array.prototype.slice.call(arguments) 

     return function(value ,index, array){
       var scope = $scope;

       for(var i = 0 ; i<arr.length ;i++) {
          if(value.Id == scope[arr[i]]) return false;
       }

       return true;

     }
  }

Here is an example

Upvotes: 1

jme11
jme11

Reputation: 17407

Nearly got it:

var app = angular.module('demo', []);

app.controller('MainCtrl', function($scope) {
  $scope.q1 = '';
  $scope.q2 = '';
  $scope.q3 = '';
    
  $scope.questions = [
    { Id: 1, Question: '1 Question' },
    { Id: 2, Question: '2 Question' },
    { Id: 3, Question: '3 Question' },
    { Id: 4, Question: '4 Question' },
    { Id: 5, Question: '5 Question' }
  ]; 
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="MainCtrl">
  <form name="form" novalidate>
    <div>
      <select name="ques1" ng-model="q1" required>
        <option value="">question</option>
        <option ng-repeat="question in questions" value="{{ question.Id }}">{{ question.Question }}</option>
      </select>
      <p class="error" ng-show="form.ques1.$error.required && form.ques1.$touched">question is required</p>
    </div>
    <div>
      <select name="ques2" ng-model="q2" required>
        <option value="">question</option>
        <option ng-repeat="question in questions | filter: ({Id: '!' + q1})" value="{{ question.Id }}">{{ question.Question }}</option>
      </select>
      <p class="error" ng-show="form.ques2.$error.required && form.ques2.$touched">question is required</p>
    </div>
    <div>
      <select name="ques3" ng-model="q3" required>
        <option value="">question</option>
        <option ng-repeat="question in questions | filter: ({ Id : '!' + q1 }) | filter: ({ Id : '!' + q2 })" value="{{ question.Id }}">{{ question.Question }}</option>
      </select>
      <p class="error" ng-show="form.ques3.$error.required && form.ques3.$touched">question is required</p>
    </div>
  </form>
</div>

Upvotes: 0

Related Questions