8

我有这样的角度嵌套对象。有没有办法为嵌套属性过滤它

<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
  ]
]
4

3 回答 3

25

您也可以像这样过滤(版本 1.2.13+)

<li ng-repeat="shop in shops | filter: { locations: [{ city_id: search.locations.city_id }] }">
于 2014-05-31T12:45:18.917 回答
10

是的,如果我正确理解了您的示例,您可以。

根据您的集合的大小,计算您迭代的集合可能会更好,ng-repeat这样过滤器就不会随着模型的变化而不断地执行此操作。

http://jsfiddle.net/suCWn/

如果我理解正确的话,基本上你会做这样的事情:

$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;
};
于 2013-08-29T08:19:58.030 回答
0

更新了“Words Like Jared”答案以使用正则表达式来检查它是否包含搜索词。这种方式在您输入 1 个数字时开始过滤,因此您不必匹配整个单词

JSfiddle

    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);
    };
于 2014-12-22T21:55:31.147 回答