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
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;
}
}
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' } );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With