2014-10-06 57 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