2014-10-06 100 views
3

我有以下陣列:AngularJS通過獨特的屬性值進行過濾,並且過濾的數量

items: [ 
{ 
    id: "0", 
    name: "כיבוי אורות", 
    icon: "rooms_salon.svg", 
    type: "scenario", 
    status: 1 
}, 
{ 
    id: "1", 
    name: "הדלקת אורות", 
    icon: "rooms_salon.svg", 
    type: "scenario", 
    status: 1 
}, 
{ 
    id: "0", 
    name: "תנור מטבח", 
    icon: "rooms_salon.svg", 
    type: "heater", 
    status: 0 
}, 
{ 
    id: "1", 
    name: "מזגן מטבח", 
    icon: "rooms_salon.svg", 
    type: "ac", 
    status: 0 
}] 

我需要過濾,所以我得到的只有唯一的項目。形式和每個項目的原始量的數類型。

的堅決,我需要:

items: [ 
    { 
     type: "scenario", 
     amount: 2 
    }, 
    { 
     type: "heater", 
     amount: 1 
    }, 
    { 
     type: "ac", 
     amount: 1 
    } 
] 

什麼是這樣做的最好方法是什麼?

P.O:我需要在控制器中過濾它,而不是在ng-repeat中。

感謝配發

阿維

回答

2

你是不是做了過濾,您需要創建所需的值的新數組。

創建這樣

function Ctrl($scope){ 
    $scope.items = [ 
     { 
      id: "0", 
      name: "כיבוי אורות", 
      icon: "rooms_salon.svg", 
      type: "scenario", 
      status: 1 
     }, 
     { 
      id: "1", 
      name: "הדלקת אורות", 
      icon: "rooms_salon.svg", 
      type: "scenario", 
      status: 1 
     }, 
     { 
      id: "0", 
      name: "תנור מטבח", 
      icon: "rooms_salon.svg", 
      type: "heater", 
      status: 0 
     }, 
     { 
      id: "1", 
      name: "מזגן מטבח", 
      icon: "rooms_salon.svg", 
      type: "ac", 
      status: 0 
     }]; 

    Object.defineProperty($scope, 'filtered', { 
     get: function(){ 
      var list = {}; 
      $scope.items.forEach(function (item) { 
       if (list[item.type] === undefined) { 
        list[item.type] = 1; 
       } else { 
        list[item.type] += 1; 
       } 
      });   
      var newItems = [];  
      Object.keys(list).forEach(function(key){  
       newItems.push({ 
       type :key, 
       amount: list[key] 
       });  
      }); 
      return newItems; 
     } 
    }); 
} 
一個計算濾波值

FIDDLE

+0

感謝您的回覆。 我需要它是一個過濾器,所以當範圍內的items數組發生變化時,這也會改變。 再次感謝 Avi – 2014-10-06 12:46:09

+0

如果您想進行更改並將此作爲方法添加到您的控制器。 – Sarath 2014-10-06 12:51:28

+0

我需要每個項目被添加到items數組,也將被添加到已過濾的數組 – 2014-10-06 12:54:18

11

您可以使用angular-filtermodule,以便將物品:

$scope.items = [ 
{ 
    id: "0", 
    name: "כיבוי אורות", 
    icon: "rooms_salon.svg", 
    type: "scenario", 
    status: 1 
}, 
{ 
    id: "1", 
    name: "הדלקת אורות", 
    icon: "rooms_salon.svg", 
    type: "scenario", 
    status: 1 
}, 
{ 
    id: "0", 
    name: "תנור מטבח", 
    icon: "rooms_salon.svg", 
    type: "heater", 
    status: 0 
}, 
{ 
    id: "1", 
    name: "מזגן מטבח", 
    icon: "rooms_salon.svg", 
    type: "ac", 
    status: 0 
}] 

$scope.content = $filter('countBy')($scope.items,'type'); 

這裏你有一個工作plunker

+0

謝謝。 'angular-filter'模塊比我自己的Javascript更容易獲得這個功能並且每次都創建新的'Objects'。 +1 – 2015-01-25 16:23:41

+0

@boindiil完美,這應該是被接受的解決方案。 – 2015-02-09 19:21:01