2013-08-29 285 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); 
    };