Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS trying to understand the js filter

Tags:

angularjs

Trying to understand the "filter" function of AngularJS most of the examples have the filters on the view/HTML side but I need it on the controller/JS side.

This works

  $scope.getPickedPeopleCount = function(){
    var thisCount = 0;
    angular.forEach($scope.allPeople, function(person){
      if(person.PICKED){thisCount++}
    });
    return thisCount;
  }

but this fails

  $scope.getPickedPeopleCount = function(){
    return $scope.allPeople.filter(PICKED:'true').length;
  }

Obviously my syntax is wrong, can someone point me in the right direction

like image 308
Lance Avatar asked Jan 08 '13 17:01

Lance


2 Answers

To use a filter in a controller, you must inject the $filter service and then request the filter by name:

function MyCtrl ( $scope, $filter ) {
  var filter = $filter('filter'); // could be orderBy, etc.

  // more code...

  $scope.getPickedPeopleCount = function () {
    return filter( $scope.allPeople, { PICKED: 'true' } ).length;
  }
}
like image 142
Josh David Miller Avatar answered Oct 22 '22 13:10

Josh David Miller


In additional to @Josh's answer, filters (the pre-defined Angular ones, and your own custom ones) can also be injected into controllers, directives, custom filters, etc. using the filterNameFilter syntax. E.g., filterFilter, dateFilter, myCoolSortFilter, etc. From the $filterProvider docs:

The filter function is registered with the $injector under the filter name suffixed with Filter.

You can be more specific about real dependencies this way (although injecting $filter gives you access to all of the Angular filters).

function MyCtrl ( $scope, filterFilter ) {
  // more code...

  $scope.getPickedPeopleCount = function () {
    return filterFilter( $scope.allPeople, { PICKED: 'true' } );
  }
}
like image 31
Mark Rajcok Avatar answered Oct 22 '22 12:10

Mark Rajcok