user2465164
user2465164

Reputation: 937

AngularJS using a function as a filter

A have an app where the filter for the content changes based on what button is clicked. For more of the straightforward filters, I've been able to figure it out. But now I'd like to create a filter that shows content that has a value within a certain range.

Here is the function I'm trying to use:

$scope.isGood = function(item){
    if(!isNan(item.rating)){
        return (item.rating>49);
    }
    return alert("Something broke!!");
    //returns true if the item has a high rating (is good, 50+)
    //returns false if the item has a poor rating (is bad, 49-)
}

Because the filter changes based on what part of navigation is clicked, and the navigation is dynamic, for the on-click of each navigation button, I run a function that grabs the filter from its link.filter section and places it into $scope.selectedFilter, a variable that is used in my ng-repeat like so:

<tr class="progress" ng-repeat="idea in ideas | filter:selectedFilter">

Since I have a handful of filters, rather than inject my own $filter and require to chain a bunch together, I'd like to write something that will fit in the $scope.selectedFilter variable, since I'd only like one filter on at a time anyways.

Here is an example of the way the dynamic navigation is set-up:

$scope.links = [
    {'name':'About', //title that will be displayed on the link
    'URL': '#/about', //URL/view that the link will lead to/show
    'filter':'' //view may simply change so some info is hidden or revealed
    },
    {'name':'Active',
    'URL': '#/active',
    'filter': {active: true}  //these {active...} buttons are straightforward and work
    },
    {'name':'Inactive',
    'URL': '#/active',
    'filter':{active: false}
    },
    {'name':'Good Rating',
    'URL': '#/active',
    'filter': 'isGood(item.rating)' //this is the function I want to filter by when clicked
    },
    {'name':'Bad Rating',
    'URL': '#/active',
    'filter':'!isGood(item.rating)'
    }
];

Here is my content I want to filter:

$scope.ideas = [
    {'title':'Title A',
    'rating': 80,
    active: true
    },
    {'title':'Title B',
    'rating': 55, //this would have a "good rating"
    active: false
    },
    {'title':'Title C',
    'rating': 10, //this would have a "bad rating"
    active: true
    }
];

But I can't get my filter to work and I'm unsure where I'm going wrong. I'm rather new to Angular, did I botch my syntax somewhere? I was trying to copy the waythis answer was written, but no-luck.

Any help would be appreciated. Thanks!

Upvotes: 0

Views: 298

Answers (1)

Strille
Strille

Reputation: 5781

The problem is that the filter value was defined as a string, it needs to be a real function. This function can then call isGood in turn. So the following should work:

{
   'name':'Good Rating',
   'URL': '#/active',
   'filter': function(item) {
      return $scope.isGood(item.rating);
    }
}

Upvotes: 1

Related Questions