2015-06-18 45 views
1

我已經列出了一些項目,需要按優先級將它們整理成列表。agularjs自定義訂單和限制

items = [ 
    {'type': 2, 'priority': 1, 'name': 'one'}, 
    {'type': 1, 'priority': 2, 'name': 'two'}, 
    {'type': 1, 'priority': 3, 'name': 'three'}, 
    {'type': 1, 'priority': 4, 'name': 'four'}, 
    {'type': 1, 'priority': 5, 'name': 'five'}, 
    {'type': 2, 'priority': 6, 'name': 'six'}, 
] 

而我需要按ng-repeat按優先級排序,並按類型分開。在一個列表type值的最大總和應爲4。所以輸出應該像(由name

['one', 'two', 'three', 'four'] 
['five', 'six'] 
+1

什麼是這裏的問題是什麼呢?還是你希望我們爲你做這項工作? –

+0

我試過寫我自己的邏輯,但沒有奏效。完全不知道從什麼開始。而不是要求爲我做所有事情,只要指出我的方式。 – gordon33

+0

在控制器中安排你的數據,使用像lodash這樣的東西來幫助你處理你的數據https://lodash.com/ –

回答

1

隨着Underscorejs你可以嘗試:

var newItems = _.chain(items).sortBy('priority').groupBy('type').value(); 

終於可以巡迴的新數組以ng-repeat表示。

編輯:這裏是的jsfiddle:http://jsfiddle.net/wb5d5pfs/

1

通過自定義角filter你可以過濾你的NG-重複像下面或在這裏jsfiddle演示。

而不是forEach循環,您也可以使用lodash或下劃線方法(例如groupBy('type')。

使用角度過濾器,您也可以像這樣在jsfiddle中執行此操作,而且不需要自定義過濾器。

angular.module('demoApp', []) 
 
    .filter('filterByType', TypeFilter) 
 
    .value('MAX_ITEMS', 4) 
 
    .controller('mainController', MainController); 
 

 
function TypeFilter($filter, MAX_ITEMS) { 
 
    return function(input, selectedType) { 
 
     var out = [], count=0, 
 
      ordered = $filter('orderBy')(input, 'priority'); 
 
     //console.log("filter start", ordered); 
 
     
 
     angular.forEach(ordered, function(obj, index) { 
 
      if (obj.type == selectedType.type && 
 
       count < MAX_ITEMS) { 
 
       out.push(obj); 
 
       count++; 
 
      } 
 
     }); 
 
     //console.log(out); 
 
     return out; 
 
    } 
 
} 
 

 
TypeFilter.$inject = ['$filter', 'MAX_ITEMS']; 
 

 
function MainController() { 
 
    
 
    this.filterTypes = [ 
 
      {type: 1}, 
 
      {type: 2} 
 
     ]; 
 
    this.type = this.filterTypes[0]; 
 
    this.items = [ 
 
     {'type': 2, 'priority': 1, 'name': 'one'}, 
 
     {'type': 1, 'priority': 2, 'name': 'two'}, 
 
     {'type': 1, 'priority': 3, 'name': 'three'}, 
 
     {'type': 1, 'priority': 4, 'name': 'four'}, 
 
     {'type': 1, 'priority': 5, 'name': 'five'}, 
 
     {'type': 2, 'priority': 6, 'name': 'six'}, 
 
    ]; 
 
     
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="demoApp" ng-controller="mainController as ctrl"> 
 
    Filter by type: 
 
    <select ng-model="ctrl.type" ng-options="opt.type for opt in ctrl.filterTypes"></select> 
 
    <p>selected type: {{ctrl.type.type}}</p> 
 
    <ul> 
 
     <li ng-repeat="item in ctrl.items |filterByType:ctrl.type"> 
 
      {{item.name}} 
 
     </li> 
 
    </ul> 
 
</div>

+0

這個很好。但我想按類型總數分割列表: ['one','two','three','four']; ['五','六']。我的意思是你循環項目的優先級和計數總類型總和,而它等於5,你應該開始製作一個新的列表。 – gordon33

+0

我不確定我是否正確理解它。但是將過濾的數據分成更多的數組可以像這樣工作。請看看[小提琴](http://jsfiddle.net/awolf2904/g296ytj9/2/)。 – AWolf