gpt4 book ai didi

javascript - 如何在 AngularJS 的 Controller 中使用独特的过滤器

转载 作者:行者123 更新时间:2023-11-30 07:33:59 24 4
gpt4 key购买 nike

我想在 Controller 中按唯一类别过滤数组,然后在 html 页面中将过滤后的数组与 ng-repeat 一起使用。我的数组是:

$scope.tabs = [
{OBJECTID:1, TYPES:8, Category:"Pharmacies",Name_EN:"antonis" , text : "Home"},
{OBJECTID:2, TYPES:8, Category:"Opticians",Name_EN:"antonis" , text : "Games"},
{OBJECTID:3, TYPES:8, Category:"Doctors", Name_EN:"antonis" , text : "Mail"},
{OBJECTID:4, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Car"},
{OBJECTID:5, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Profile"},
{OBJECTID:6, TYPES:8, Category:"Clinics", Name_EN:"antonis" , text : "Favourites"},
{OBJECTID:7, TYPES:8, Category:"Pharmacies",Name_EN:"antonis" , text : "Chats"},
{OBJECTID:8, TYPES:4, Category:"Sights",Name_EN:"antonis" , text : "Settings"},
{OBJECTID:9, TYPES:4, Category:"Meuseums",Name_EN:"antonis" ,text : "Home"},
{OBJECTID:10, TYPES:4, Category:"Meuseums",Name_EN:"antonis1" , text : "Home"}

];

过滤后的数组是这样的:

$scope.FilteredArray = [
{Category:"Pharmacies"},
{Category:"Opticians"},
{Category:"Doctors"},
{Category:"Clinics"},
{Category:"Sights"},
{Category:"Meuseums"},

];

提前致谢。

最佳答案

controller 中使用 unique filter 并在过滤后的数组上应用 ng-repeat

//Filtered array
$scope.filteredArray = $filter('unique')($scope.tabs,'Category');

<ul>
<li ng-repeat="tab in filteredArray">{{tab.Category}}</li>
</ul>

过滤器

angular.module('myapp').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;
};
});

FULL EXAMPLE

关于javascript - 如何在 AngularJS 的 Controller 中使用独特的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com