1

In my angular application, I came into a filter related issue. I have reproduced this issue with a simple live demo as bellow:

https://jsfiddle.net/baoqger/fpo3j6gx/2/

<div ng-app="app">
    <div ng-controller="filterCtrl as f">
        <input type="text" ng-model="f.inputdata"></input>
        <span ng-click="f.setFilter('lowercase')">First Filter</span>
        <span  ng-click="f.setFilter('uppercase')">Second Filter</span>
    <div ng-bind="f.inputdata | f.filtername"></div>
</div>

click First Filter or Second Filter will trigger the setFilter function.

function filterCtrl() {
    this.setFilter = function ( name ){
        this.filtername = name;
    }.bind(this);
}

angular
    .module('app', [])
    .controller('filterCtrl', filterCtrl)

In the controller, the filtername will be set to lowercase or upper case, depends on which button was clicked as mentioned above.
Then set the filtername as filter method as below:

<div ng-bind="f.inputdata | f.filtername"></div>

But based on the error message, it seems that angular system can't support such usage. Any help?

1 Answer 1

1

Try this solution:

Javascript:

.controller('filterCtrl', ['$filter' function($filter){
     var self = this;
     self.setFilter = function(name){
         self.filter = $filter(name);
     }
}]);

HTML:

<div ng-app="app">
    <div ng-controller="filterCtrl as f">
        <input type="text" ng-model="f.inputdata"></input>
        <span ng-click="f.setFilter('lowercase')">First Filter</span>
        <span  ng-click="f.setFilter('uppercase')">Second Filter</span>
    <div ng-bind="f.filter?f.filter(f.inputdata):f.inputdata"></div>
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this solution works for this case. If I need to filter list data, like <div ng-repeat="item in itemlist | dynamicFilter">. Can this solution still work?
At this case: <div ng-repeat="item in f.filter(itemlist, additionalArgIfNeeded)">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.