AngularJS - Use function as filter inside controller

40 Views Asked by At

If I have a filter defined

app.filter('filterName', function() {
    return function(var) {
        // Some filter stuff
    }
}

I can invoke it on controller doing $filter('filterName')($scope.someObj);.

But, here is my question, if I have a function that use as a filter

$scope.myFilterFunction = function() {
    return true;
}

In my HTML

<p ng-repeat="item in items | filter:myFilterFunction">{{item}}</p>

How can I use this function filter in the controller (I have tested with $filter but throws an error).

Thanks in advance.

2

There are 2 best solutions below

5
Khai Kiong On

If you already implement the custom filter filterName, why not use it?

Try

<p ng-repeat="item in items | filterName">{{item}}</p>

Updated

You just missing the parentheses.

<p ng-repeat="item in items | filter:myFilterFunction()">{{item}}</p>
0
skdonthi On

Inject $filter in the controller and use it with your filter name.

controller.$inject = ['$filter'];

function controller($filter){
// code here    
  $filter('filterName')(arg1,arg2);
//
}