angular的unique过滤器

Angular

Angular的过滤器是非常实用的一个功能,过滤器的功能是为了格式化数据,
只要有数据表达式的地方就能使用过滤器。
除去使用默认的几个过滤器,我们还可以自己定义过滤器。

其中unique是非常实用的一个过滤器,在angular-ui插件中,已经集成了unique方法,
可以在angular-ui/angular-ui-OLDREPO
中看到,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Filters out all duplicate items from an array by checking the specified key
* @param [key] {string} the name of the attribute of each object to compare for uniqueness
if the key is empty, the entire object will be compared
if the key === false then no filtering will be performed
* @return {array}
*/
angular.module('ui.filters').filter('unique', function () {

return function (items, filterOn) {

if (filterOn === false) {
return items;
}

if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];

var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};

angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;

for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}

});
items = newItems;
}
return items;
};
});

同时,有一个angular插件,提供了不同的filter,angular-filter,
可以直接注入该插件,实现我们需要的unique过滤器