2016-01-27 50 views
1

如何將數組中的對象放入數組中,並使用過濾器重複ng?ng-array中數組中的對象如何與filter重複?

我有一個數組與對象,我希望由他們的國家這個對象組。

樣品:我想有這樣的結果:

Free : Australia, India, United States 
Pay : Australia 
Not Pay : Australia, India 

來自:

{ 
"id": 1, 
"offer": [ 
    { 
     "id": 9806, 
     "country": { 
      "name": "Australia" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      }, 
      { 
       "code": "Pay" 
      }, 
      { 
       "code": "Not Pay" 
      } 
     ] 
    }, 
    { 
     "id": 9807, 
     "country": { 
      "name": "India" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      }, 
      { 
       "code": "Not Pay" 
      } 
     ] 
    }, 
    { 
     "id": 9808, 
     "country": { 
      "name": "United States" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      } 
     ] 
    } 
], 
}, 
{ 
"id": 2, 
"offer": [ 
    { 
     "id": 9806, 
     "country": { 
      "name": "Australia" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      }, 
      { 
       "code": "Not Pay" 
      } 
     ] 
    }, 
    { 
     "id": 9807, 
     "country": { 
      "name": "Mexico" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      } 
     ] 
    }, 
    { 
     "id": 9808, 
     "country": { 
      "name": "United States" 
     }, 
     "code_show": [ 
      { 
       "code": "Free" 
      } 
     ] 
    } 
] 
} 

我的代碼嘗試這樣做:

<ul ng-repeat="(key, value) in offer.code_show | groupBy: 'code_show.code'"> 
    {{ key }} 
    <li ng-repeat="country in value"> 
    : {{ country.name }} 
    </li> 
</ul> 

回答

2

這可能中做得更好控制器 - 主要會導致您擁有不同的數據結構:

$scope.groupedByCode = {}; 
$scope.offer.forEach(function(obj) { 
    obj["code_show"].forEach(function(code) { 
     if (!$scope.groupedByCode[code]) { 
      $scope.groupedByCode[code] = []; 
     } 

     $scope.groupedByCode[code].push(obj); 
    }); 
}); 

現在,你必須在代碼的名稱關鍵字的每個offer對象,那麼就使視圖:

<ul ng-repeat="(key, value) in groupedByCode"> 
    {{ key }} 
    <li ng-repeat="country in value"> 
     : {{ country.country.name }} 
    </li> 
</ul> 
相關問題