Inject $scope into filter (AngularJS)

可紊 提交于 2019-12-04 17:49:22
michael

you may have parameters to your custom filter.

suppose you have an input field:

<input ng-model="myParam">

and an ng-repeat like yours:

<tr ng-repeat="(key, machine) in machines | customFilter:myParam | orderObjectBy:'name':false" >

then you may access this parameter in your custom filter:

toolApp.filter('customFilter', [function(){
    return function(machines, myParam){
        var result = {};

        angular.forEach(machines, function(machine, key){
            if(machine.name.contains(myParam)){
                result[key] = machine;
            }
        });
        return result;
    };
}]);

note: Pay attention that the myParam value is initialized with an "undefined" value. You have to set a default value in the controller or handle it in the customFilter. Otherwise you will only see your list, after you started typing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!