Search code examples
javascriptangularjsangular-filters

AngularJS Filter values which are in another array


I'm just getting started with using filters in AngularJS. What I want to do is to link compositions to products, using a simple Select-box.

In my $scope, I have an object "product", which, among other values, contains an array "technicalProducts". This array contains all compositions, which have been linked to my current product. The array "allCompositions" holds all existing compositions. No, whenever a composition has been linked, I want to remove it from the Select-options. I thought the easiest way to do this was by using a filter.

Unfortunately, this won't work:

<select class="form-control" name="compositions" id="compositions" ng-options="composition as composition.sysName for composition in allCompositions track by composition.sysName | filter:product.technicalProducts" ng-model="selComposition"></select>

Any advice?


Solution

  • filter is good for your scenario here. But you have to define a custom filter because the default filter only works for simple string.

    // input for the target collection, args for the filter condition.
    angularModule.filter('testFilter', function(input, args) {
      if (!args || args = '') return input;
      return input.filter(function(item) {
        return args.indexOf(item) === -1;
      });
    })
    

    then use it this way:

    ng-options="composition as composition.sysName for composition in allCompositions | testFilter: product.technicalProducts track by composition.sysName"
    

    var app = angular.module("app", []);
    
    
    app.filter('testFilter', function() {
      return function(input, args) {
        if (!args || args === '') return input;
        return input.filter(function(item) {
          return args.indexOf(item) === -1;
        });
      };
    });
    
    app.controller("myCtrl", function($scope) {
      $scope.selectedItem = 2;
    
      $scope.testArr = [
        1, 2, 3, 4, 5, 6, 7, 8
      ];
      $scope.testArr2 = [
        1, 3, 5, 7
      ];
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
    <div ng-app="app" ng-controller="myCtrl">
      <select ng-options="item for item in testArr | testFilter: testArr2" ng-model="selectedItem"></select>
    </div>