0

How would I go about setting the filter property on an ng-repeat dynamically?

Here is my template...

<div class="list-group">
    <div ng-repeat="article in articles | activeFilter">
      <a href="#" class="list-group-item">
        <h3 class="list-group-item-heading">{{ article.title }}</h3>
        <h4 class="list-group-item-text">{{ article.author }}</h4>
          <p class="list-group-item-text">"{{ article.blurb }}"</p>
      </a>
    </div>
  </div>

Where "activeFilter" is a property I want to set via the controller...

...

$scope.activeFilter = 'someFilterType'

...

And the filter looks like this...

.filter('someFilterType', function () {
      return function (items) {
        var rv = [];
        for (var p in items) {
          if (items[p].myFilterProp === false)
          rv.push(items[p]);
        }
        return rv;
      }
    })

I would think I could dynamically change the ng-repeat's filter in this way, but it doesn't seem to be working and I'm not sure why.

4
  • Why aren't you calling to the filter directly ? Commented Aug 9, 2013 at 15:32
  • It's because your scope variable is a string. To do what you want you may have to ditch the custom filter module, and use a controller function as a filter. Commented Aug 9, 2013 at 15:38
  • As in, ng-repeat="e in array" | myCustomFunction() ? Commented Aug 9, 2013 at 15:39
  • possible duplicate of dynamically change the filter expression Commented Aug 9, 2013 at 16:05

1 Answer 1

2

Try something like this:

HTML

ng-repeat="article in articles | filter:activeFilter[filter]"

Controller:

$scope.filter = "name1";

$scope.activeFilter = {
    name1: $scope.someFilterFunction,
    name2: $scope.someOtherFilter,
    name3: $scope.andAnother
};

$scope.someFilterFunction = function() {
    var rv = [];
    for (var p in items) {
        if (items[p].myFilterProp === false)
            rv.push(items[p]);
        }
    return rv;
};
Sign up to request clarification or add additional context in comments.

4 Comments

Binding the function in this way will certainly do the trick, but it really cuts down on the flexibility of what I was trying to do.
I edited it, how about something like that? Then you can just change the value of filter to 1 or 2 and have different filters defined.
My point was to define the activeFilter according to a button clicked in the view, where the view's controller would reach out to a service and update the parameter. Any controllers observing that service would then update their views accordingly.
This is quite nifty, but not that extensible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.