I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller?
This is what I've tried so far:
function myCtrl($scope,filter1) { // i simply used the filter function name, it is not working. }
There is $filter service which is used in our AngularJS controller. In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope.
function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44]. filter(isBigEnough); console. log("Test Value : " + passed ); On compiling, it will generate the same code in JavaScript.
Inject $filter to your controller
function myCtrl($scope, $filter) { }
Then wherever you want to use that filter, just use it like this:
$filter('filtername');
If you want to pass arguments to that filter, do it using separate parentheses:
function myCtrl($scope, $filter) { $filter('filtername')(arg1,arg2); }
Where arg1
is the array you want to filter on and arg2
is the object used to filter.
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