一些故障排除编写自定义筛选器

时间:2016-04-14 17:13:48

标签: javascript angularjs

我在项目中使用angularjs。

我想在ng-repeat中过滤我的数组。

这是HTML:

<tbody>
    <tr ng-repeat="sensorData in list.sensorsData |
                                filterByAlert:list.alertTags">
        <td>
            <div class="container-fluid">
                <div class="row">
                    <div class="text-center">{{ sensorData.Area }}</div>
                </div>
            </div>
        </td>
    </tr>
</tbody>

这是查看list.sensorsData对象数组的方法:

enter image description here

以下是list.alertTags对象数组的外观:

enter image description here

我需要在ng-repeat元素中只显示list.sensorsData行,其中alertType属性值等于list.alertTags中的Id proiperty。

为此我编写了这个过滤器:

(function () {
    "use strict";

    angular.module("sensorsData").filter('filterByAlert', filterByAlert);

    function filterByAlert() {
        var result = [];
        return function (sensorRecords, alertTypes) {
            if (!sensorRecords)
                return;
            if (!alertTypes)
                return;
            angular.forEach(sensorRecords, function (sensorRecord, key) {
                angular.forEach(alertTypes, function (alertType, key2) {
                    if (sensorRecord.AlertType == alertType.Id ) {
                        result.push(sensorRecord);
                    }
                })
            });
            return result;
        }
    };
})();

但是当过滤器被触发时我得到了这个错误:

angular.js:13424 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: sensorData in list.sensorsData |
                                    filter:filterByAddress |
                                    orderBy:sortType:sortReverse |
                                    filterByAlert:list.alertTags, Duplicate key: object:8, Duplicate value: {"Id":8,"Address":"125 king g.str","AlertType":3,"Area":"North","MeasureDate":"2012-10-12T16:10:00","MeasureValue":-1}

我的自定义过滤器中的逻辑似乎有问题。

我知道为什么会收到错误?以及如何修复它?

1 个答案:

答案 0 :(得分:0)

track by $index添加到ng-repeat。

<tr ng-repeat="sensorData in list.sensorsData | filterByAlert:list.alertTags  track by $index">