我有像这样的角度嵌套对象。 有没有办法过滤它的嵌套属性
<li ng-repeat="shop in shops | filter:search">
search.locations.city_id = 22
我只显示父元素,但希望按两者进行过滤,例如:
search =
category_id: 2
locations:
city_id: 368
[
name: "xxx"
category_id: 1
locations: [
city_id: 368
region_id: 4
,
city_id: 368
region_id: 4
,
city_id: 368
region_id: 4
]
,
name: "xxx"
category_id: 2
locations: [
city_id: 30
region_id: 4
,
city_id: 22
region_id: 2
]
]
答案 0 :(得分:23)
您也可以像这样过滤(版本1.2.13 +)
<li ng-repeat="shop in shops | filter: { locations: [{ city_id: search.locations.city_id }] }">
答案 1 :(得分:9)
是的,如果我理解你的例子,你可以。
根据您的集合的大小,最好计算您在ng-repeat
中迭代的集合,以便在模型更改时过滤器不会持续执行此操作。
如果我理解正确的话,基本上你会做这样的事情:
$scope.search = function (shop) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
var found = false;
angular.forEach(shop.locations, function (location) {
if (location.city_id === parseInt($scope.selectedCityId)) {
found = true;
}
});
return found;
};
答案 2 :(得分:0)
更新了“像Jared这样的单词”的答案,使用正则表达式来检查它是否包含searchterm。这种方式在您键入1个数字时开始过滤,因此您不必匹配整个单词
angular.forEach(shop.locations, function (location) {
if (checknum(location.city_id)) {
found = true;
}
});
function checknum(num){
var regx = new RegExp($scope.selectedCityId);
return regx.test(num);
};