Inject $scope into filter (AngularJS)

14,075

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.

Share:
14,075
zois
Author by

zois

Updated on September 10, 2022

Comments

  • zois
    zois over 1 year

    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