如何通過另一個數組中存在的屬性過濾數組?如何在AngularJS中實現過濾器?
我在我的控制這兩個數組:
this.items = [{ "Id": 1, "TypeId": 1, "name": "Michael" },
{ "Id": 2, "TypeId": 2, "name": "Helga" },
{ "Id": 3, "TypeId": 1, "name": "Max" },
{ "Id": 4, "TypeId": 2, "name": "Ann" }];
this.filterBy = [{ "Id": 1, "gender": "Male" },
{ "Id": 2, "gender": "female" }];
,這裏是我的NG-重複在視圖模板:
<tr ng-repeat="item in list.items">
<td>
<div class="container-fluid">
<div class="row">
<div class="text-center">{{ item.name }}</div>
</div>
</div>
</td>
</tr>
這裏是生成的觀點:
在某些時候,我想按性別過濾項目數組以顯示我上面的視圖僅限於女性或僅男性。
我試圖執行過濾器,像這樣:
(function() {
"use strict";
angular.module("sensorsData").filter('filterByGender', filterByGender);
function filterByGender() {
var result = [];
return function (items, filterBy) {
if (!items)
return;
if (!filterBy)
return;
angular.forEach(items, function (item) {
angular.forEach(filterBy, function (f) {
if (item.TypeId == f.Id) {
result.push(item);
}
})
});
return result;
}
};
})();
在這裏,我如何使用它在視圖模板:
<tr ng-repeat="item in list.items | filterByGender:list.filterBy">
<td>
<div class="container-fluid">
<div class="row">
<div class="text-center">{{ item.name }}</div>
</div>
</div>
</td>
</tr>
的情況下,所需的視圖如果filterBy陣列那樣的內容:
this.filterBy = [{ "Id": 1, "gender": "Male" }];
該視圖應僅顯示TypeId = 1的項目行。
像這樣:
但上面的過濾器不能正常工作。
並在調試我得到這個錯誤:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: r in list.arr | filterByAlert:list.filterBy, Duplicate key: object:8, Duplicate value: {"Id":1,"TypeId":1,"name":"Michael"}
http://errors.angularjs.org/1.5.3/ngRepeat/dupes?p0=r%20in%20list.arr%20%7C…%3A8&p2=%7B%22Id%22%3A1%2C%22TypeId%22%3A1%2C%22name%22%3A%22Michael%22%7D
at angular.js:68
at ngRepeatAction (angular.js:28799)
at $watchCollectionAction (angular.js:16734)
at Scope.$digest (angular.js:16869)
at Scope.$apply (angular.js:17133)
at done (angular.js:11454)
at completeRequest (angular.js:11652)
at XMLHttpRequest.requestLoaded (angular.js:11593)
爲什麼不工作的過濾器?我如何創建一個過濾器來按性別顯示項目?
這:
angular.js:13424 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.5.3/$rootScope/infdig?p0=10&p1=%5B%5D
at angular.js:68
at Scope.$digest (angular.js:16907)
at Scope.$apply (angular.js:17133)
at done (angular.js:11454)
at completeRequest (angular.js:11652)
at XMLHttpRequest.requestLoaded (angular.js:11593)(anonymous function) @ angular.js:13424
angular.js:17136 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.5.3/$rootScope/infdig?p0=10&p1=%5B%5D
這:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
爲什麼不工作的過濾器?我如何創建一個過濾器來按性別顯示項目?
是否有一個特別的原因,你不是'typeId'過濾列表?或者你已經把相關數據看作是另一個變量? – Jhecht
@Jhecht,我需要根據filterBy數組中的更改過濾生成視圖中的數據。 – Michael
「上面的過濾器無法正常工作」是什麼意思?結果是什麼?你期望什麼? –