2013-08-29 288 views
7

我有像这样的角度嵌套对象。 有没有办法如何筛选它嵌套属性Angularjs过滤器嵌套对象

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

回答

8

是的,你可以,如果我正确理解你的例子。

根据您的集合的大小,计算您在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; 
}; 
23

您还可以过滤像这样更新(版本1.2.13+)

<li ng-repeat="shop in shops | filter: { locations: [{ city_id: search.locations.city_id }] }"> 
+1

好这个工作,但默认情况下只输入后结果不会显示。 http://jsfiddle.net/suCWn/12/ – zajca

+1

我稍微修改了你的小提琴:[link](http://jsfiddle.net/suCWn/15/) – martinoss

+2

@zajca你可以通过在控制器中分配一个模型值来解决这个问题:'$ scope.selectedCityId ='''。在手动更改输入之前加载所有项目的效果 –

0

“像Jared这样的词”的答案是使用正则表达式来检查它是否包含searchterm。当你在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); 
    };