如何将输入值作为参数传递到Angularjs中的自定义过滤器

时间:2016-04-21 20:28:43

标签: javascript angularjs

我想将两个参数传递给自定义过滤器' 从' '到' 到我自定义的过滤器中在我的控制器中创建。

在这里,您可以看到我创建的自定义过滤器:

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

视图如下:

<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>

由于某种原因,这不起作用。 好吧,如果我这样调用过滤器:filter: AdminReportsWorksnaps.filterMinutes('totalMinutes', 5000,6000)"它的工作原理非常好..我只是看不出如何从文本框中传递输入值。

由于

2 个答案:

答案 0 :(得分:1)

将其作为:分隔(假设您使用controllerAs模式与vm别名)

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

因此,在上述情况下,您需要在过滤器中预期4个参数,第一个参数为AdminReportsWorksnaps.data,第二个参数为totalMinutes,第三个fromMinutes&amp;最后一个是toMinutes

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;
    });
};

答案 1 :(得分:0)

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.