Inject $scope into filter (AngularJS)

♀尐吖头ヾ 提交于 2019-12-09 21:28:19

问题


What I'm trying to do:

Im using a ng-repeat directive on an associative array, which I want to filter. The build in angular filter isn't working on associative arrays/hashes. Because of that, I'm trying to write my own filter (inspired by http://angularjs.de/artikel/angularjs-ng-repeat; it's in german, but the important code is below the headline "Beispiel 2: Filtern von Hashes mittels eigenem Filter" which means "Example 2: Filter Hashes with your own filter").

The ng-repeat:

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

note: orderObjectBy is also a customFilter.

The filter:

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

        angular.forEach(machines, function(machine, key){
            /*if(machine.name.contains(filter)){
                result[key] = machine;
            }*/
            //if(machine.name.contains("a")){
                result[key] = machine;
            //}
        });
        return result;
    };
}]);

The filter works with a hardcoded "filter-criterium". But I want to have a textbox above the list, in which the user can enter the "filter-criterium". My Problem is, that i don't know how to insert this value into the filter. I don't find much on the Internet and what i found, didn't work for me.

Has anyone an idea how to insert the value oder maybe a different approach.

Huge thanks in advance for every answer! If you need more information, let me know! I tried to keep it short :>.

Greetings from Germany


回答1:


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.



来源:https://stackoverflow.com/questions/21583069/inject-scope-into-filter-angularjs

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