简体   繁体   中英

How to pass input values as arguments into the custom filter in Angularjs

I want to pass two argument to the custom filter ' from' and 'to' into the custom filter I have created in my controller.

Here you can see my custom filter I have created:

    vm.filterMinutes = function (prop, from, to) {
        return function (item) {
            return item[prop] >= from && item[prop] <= to;
        };
    };

And the view looks like this:

<label>Search from: <input ng-model="fromMinutes"></label>
<label>Search from: <input ng-model="toMinutes"></label>

    <tr style="cursor: pointer;" ng-repeat="student in AdminReportsWorksnaps.data | filter: AdminReportsWorksnaps.filterMinutes('totalMinutes', fromMinutes,toMinutes)">
                <td>{{ student.studentId }}</td>
                <td>{{ student.firstName }}</td>
                <td>{{ student.lastName }}</td>
                <td>{{ student.municipality }}</td>
                <td class="total success">{{ student.totalMinutes | number}}</td>
   </tr>

For some reason this is not working. Well, If I Call filter like this: filter: AdminReportsWorksnaps.filterMinutes('totalMinutes', 5000,6000)" it works perfectly fine.. I just cant see how can I pass the input values from the textboxs.

Thanks

Pass it as : separated (Assuming you are using controllerAs pattern with vm alias)

ng-repeat="student in AdminReportsWorksnaps.data | filter: AdminReportsWorksnaps.filterMinutes: 'totalMinutes': fromMinutes: toMinutes"

So in above case you need to expect 4 parameter in a filter, 1st parameter would be AdminReportsWorksnaps.data , 2nd would be totalMinutes , 3rd fromMinutes & last would be toMinutes value

vm.filterMinutes = function (collection, prop, from, to) {
    //collection would have 
    console.log("AdminReportsWorksnaps.data", collection)
    console.log(prop, from, to);
    return (collection || []).filter(function (item) {
        return item[prop] >= from && item[prop] <= to;
    });
};

It look like you're using a controllerAs , so why don't use the controller alias for the models too :

<label>Search from: <input ng-model="AdminReportsWorksnaps.fromMinutes"></label>
<label>Search from: <input ng-model="AdminReportsWorksnaps.toMinutes"></label>

<tr style="cursor: pointer;" ng-repeat="student in AdminReportsWorksnaps.data | filter: AdminReportsWorksnaps.filterMinutes('totalMinutes', AdminReportsWorksnaps.fromMinutes, AdminReportsWorksnaps.toMinutes)">
    <td>{{ student.studentId }}</td>
    <td>{{ student.firstName }}</td>
    <td>{{ student.lastName }}</td>
    <td>{{ student.municipality }}</td>
    <td class="total success">{{ student.totalMinutes | number}}</td>

It should works like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM