Tomas Aschan
Tomas Aschan

Reputation: 60644

Filter a list in-place with the angular $filter service

I have a couple of filters which are working fine, and which I've so far used only through pipes in my HTML templates. Now, I have a use case where I'd like to do the same kind of filtering, but in the controller of a directive.

I know I can use the angular $filter service to get access to the filters, using

var filtered = $filter('myFilter')(unfiltered);

but my use-case requires that the lists are filtered in-place, i.e. I can not re-bind the variable (lest I would loose the bindings to other places where the same variable might be used).

I can't find anything about this in the official docs, but I don't want to give up hope just yet =)

Upvotes: 0

Views: 474

Answers (1)

Aviv Shaked
Aviv Shaked

Reputation: 762

I think that you are describing a case where replacing the entire array (or object) in a child scope, the parent, or sibling scopes lose the connection to the array. This happens because of the nature of scope inheritance. If you have a scope, you place an array on that scope, then have two child scopes, and replace the array on one of them, then the other child scope and parent scope will 'loose the connection'. There several ways to solve this. Here are a couple:

  1. Wrap the array with an object on the parent scope. Then reference the array in the child scopes via the object. If you do that you can change the entire array and all controllers will still reference the same array.

instead of: $scope.someArr

use: $scope.wrapper = {
   someArr: SomeArr
}

then: on the child scope reference: $childScope.wrapper.someArr

  1. You can modify the original array. Filter into a new array, then concat the arguments into an array, and apply splice:

example code:

//originalArr
var newArr// = new filtered array
var args = [0, originalArr.length].concat(newArr);
originalArr.splice.apply(this, args);

This code is conceptual only and has not been tested. The idea is that splice handles the original array and the reference to the array on all scopes stays the same.

Upvotes: 2

Related Questions