mmmoustache
mmmoustache

Reputation: 2323

angularjs: invoking custom filter from within controller

I'm trying to manipulate some JSON data using a custom angular filter and I'm having difficulty when trying to invoke it from within my controller.

As you can see in this jsfiddle, the idea is to only return items from my json with a rating higher than 6, which should return two items: items 2 & 3.

This is my filter:

.filter('greaterThan', function() {
    return function(a, b) {
        return parseInt(a) > parseInt(b);
    }
})

and I'm invoking it within my controller like so:

 var greaterThanFilter = $filter('greaterThan'),
     filteredItems = greaterThanFilter(data, {'rating': 6});

     $scope.items = filteredItems;

I've tried to model my filter and the invocation on the built-in angular filters, so I'm not sure what I'm doing wrong.

Upvotes: 0

Views: 547

Answers (1)

RamblinRose
RamblinRose

Reputation: 4963

You're not implementing the filter the way you think you are, it looks like you're sorting, but what?

This is probably more like what you are looking for, note the options parameter.

  .filter('greaterThan', function() {
    return function(data, options) {
      var result = [];
      data = data || [];
      if (options.rating != undefined) {        
        for (let i = 0; i < data.length; i++)
          if (data[i].rating > options.rating)
            result.push(data[i]);
      } 
      return result;
    }
  })

And in your controller, invoke like this

$scope.items = $filter('greaterThan')(data, {rating: 6});

I forked your fiddle, see this

Upvotes: 1

Related Questions