Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have two arrays:

$scope.arr1 = [1, 2, 3];
$scope.arr2 = [2, 3, 4];

I'm trying to:

  • ng-repeat through arr1
  • Use a custom filter to only show items from arr1 that aren't in arr2
  • The output should be 1

Here's my view:

<ul>
  <li ng-repeat="item in arr1 | matcher">
    {{item}}
  </li>
</ul>

Here's my controller:

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

app.filter('matcher', function () {
  for (var i = 0; i < $scope.arr1.length; i++) {
    for (var j = 0; j < $scope.arr2.length; j++) {
      if ($scope.arr1[i] != $scope.arr2[j])  {
        return $scope.arr1[i];
      }
    }
  }
});

app.controller('MainCtrl', function($scope) {
  $scope.arr1 = [1, 2, 3];
  $scope.arr2 = [2, 3, 4];
});

Here's my Plunker: http://plnkr.co/edit/Pd3QwMMNfmL62vvdD1kW?p=preview

Any idea how to get this custom filter working?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

You will never get access $scope inside the angular filter in any way, you should pass them as parameter inside your filter and then access them inside your filter function. For making it more cleaner you could take use of .filter & .indexOf inside your filter.

HTML

<body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="item in arr1 | matcher: arr2">
        {{item}}
      </li>
    </ul>
</body>

Code

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

app.filter('matcher', function() {
  return function(arr1, arr2) {
    return arr1.filter(function(val) {
      return arr2.indexOf(val) === -1;
    })
  }
});

app.controller('MainCtrl', function($scope) {
  $scope.arr1 = [1, 2, 3];
  $scope.arr2 = [2, 3, 4];
});

Working Plunkr

share|improve this answer
    
Perfect - thank you! – Ryan Aug 6 at 20:06
1  
Done. The 15 minute accept answer delay is really annoying. Thanks again. – Ryan Aug 6 at 20:11
1  
@Ryan It could be look something like this plnkr.co/edit/McgDHPm5KAEXJ4bEtWln?p=preview If you use _ lodash.js then it could be more simpler – Pankaj Parkar Aug 6 at 20:44
1  
@Ryan I think while creating an arrays of ids you could use _.pluck method.. – Pankaj Parkar Aug 6 at 21:09
1  
Great - thanks so much for all your help! – Ryan Aug 6 at 21:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.