2014-09-22 66 views
0

我採用了棱角分明1.2.16和過濾這樣的對象的列表:如何NG重複角濾波後聚集對象屬性

<li ng-repeat="item in filteredItems = (items | filter:query)"> 
    {{item.title}} 
</li> 

可以說我有以下

的「項目」陣
var items = [ { title: "foo", priority: 1 }, 
       { title: "bar", priority: 2 }, 
       { title: "bla", priority: 1 } ]; 

而後被過濾,用 「b」,角臺 「filteredItems」 到

filteredItems == [ { title: "bar", priority: 2 }, 
        { title: "bla", priority: 1 } ]; 

什麼我希望做我s計算每個優先級類型的出現次數,後期過濾並打印出來。例如。給定上述方案的輸出將打印priority-1 = 2, priority-2 = 1,然後在應用過濾器「b」後變爲priority-1 = 1, priority-2 = 1

我應該如何做到這一點角?

我試着創建一個新的控制器,然後使用$scope.$parent.filteredItems,但filteredItems片不動態更新。

這裏有一個plunkr http://plnkr.co/edit/uA5TgBVFVEd89dHSP0Yo

+0

檢查'$ watch',你不需要另外2個控制器。 – zsong 2014-09-22 17:37:47

回答

0

This post by Ben Nadel最接近回答我的問題就來了,加入NG-重複完成後觸發一個事件的自定義指令。但是,這比我想要的要複雜一點。

我最後的做法是向控制器添加一個自定義$過濾器,當輸入發生變化時觸發該過濾器,最後創建一個可以打印出來的摘要對象。猛擊者可以發現here

的HTML:

<input ng-model="query" type="text" ng-change="myFilter(query)" /> 

    <ul> 
     <li ng-repeat="item in items"> 
     <pre>{{item}}</pre></li> 
    </ul> 

    <h3>Summary of items</h3> 
    <p > 
     Priority-1: {{summary.p1}}<br> 
     Priority-2: {{summary.p2}} 
    </p> 

    </body> 

的App.js

var app = angular.module('app', []); 

app.controller('ParentCtrl', ['$scope', '$filter', 
    function($scope, $filter) { 

    $scope.originalItems = [{ 
     title: "foo", 
     priority: 1 
    }, { 
     title: "bar", 
     priority: 2 
    }, { 
     title: "bla", 
     priority: 1 
    }]; 

    $scope.items = $scope.originalItems; 

    var summarize = function(items) { 
     var summary = { 
     p1: 0, 
     p2: 0 
     }; 
     for (var i in items) { 
     switch (items[i].priority) { 
      case 1: 
      summary.p1++; 
      break; 
      case 2: 
      summary.p2++; 
      break; 
     } 
     } 
     return summary; 
    }; 

    $scope.myFilter = function(query) { 
     $scope.items = $filter('myFilter')($scope.originalItems, query); 
     $scope.summary = summarize($scope.items); 
    } 

    $scope.summary = summarize($scope.items); 

    } 
]); 

app.filter('myFilter', ['$filter', 
    function($filter) { 
    return function(items, query) { 
     return $filter('filter')(items, query); 
    }; 
    } 
]); 
2

更簡單的辦法,但仍不理想:

http://plnkr.co/edit/wkGKYQus2exkLycIu9XB?p=preview

HTML:

<body ng-controller="ParentCtrl"> 
    <input ng-model="query" type="text"/> 

    <ul> 
    <li ng-repeat="item in items | filter : query"> 
     <pre>{{item}}</pre></li> 
    </ul> 
    <h3>Summary of items</h3> 
    <p > 
    Priority-1: {{items | filter : query | sumFilter: '1'}}<br> 
    Priority-2: {{items | filter : query | sumFilter: '2'}} 
    </p> 
</body> 

JS:

app.filter('sumFilter', function() { 
    return function(items, value) { 
    var summary = 0; 
    for (var i in items) { 
     if (items[i].priority == value) { 
     summary++; 
     } 
    } 
    return summary; 
    } 
});