0

I'm trying to write a generic filter function like this:

var filterGenerator = function(ids) {
  return function (o) {
    return _.contains(ids, o.id); // using lodash _.contains
  }
}

I expose this on the scope like so:

$scope.myFilter = filterGenerator($scope.listOfIds);

It works on initial page load in the partial (using o in objects | filter:myFilter), but when $scope.listOfIds changes, I would expect the filtered values to change as well - however, they do not. I suspect that when I call filterGenerator($scope.listOfIds), the returned lambda is getting a separate scoped version of $scope.listOfIds that never changes, but I'm unsure how to get around this. How would I go about making sure that the lambda sees any changes to the list?

aarestad
  • 586
  • 1
  • 5
  • 19

2 Answers2

0

You're right, the filter is taking the value of $scope.listOfIds at the time it is run, and then won't update because that line of code doesn't run again.

You should have the filter take listOfIds as an argument, then pass that argument in the view.

https://stackoverflow.com/a/16227326

ng-repeat="o in objects | filter:myFilter:listOfIds"
Community
  • 1
  • 1
0

After working with Mr. Baritonehands, we decided on a better solution: We can set a particular filter on the fly like this:

$scope.filterFn = function(o) {
  return filterGenerator($scope.listOfIds)(o);
}

That way the generated function always sees what's current on the scope.

aarestad
  • 586
  • 1
  • 5
  • 19