Angular.js more complex conditional loops

允我心安 提交于 2019-12-04 16:58:19

You could write your own filter that filters out the unique dates for an outer ng-repeat, something like:

filter('unique',function(){
  return function(items,field){
    var ret = [], found={};
    for(var i in items){
      var item = items[i][field];
      if(!found[item]){
        found[item]=true;
        ret.push(items[i]);
      }
    }
    return ret;
  }
});

with the following markup:

<div ng-repeat="dateItem in items | unique:'date' | orderBy:'date'">
<h3>{{dateItem.date}}</h3>
<ul>
  <li ng-repeat="item in items | filter:dateItem.date">
    {{item.name}}
  </li>
</ul>  
</div>

Have a look at this working plnkr example -- or this updated example with adding items

However, if your going to have a lot of items (hundreds or thousands) this solution is not the most optimal. An alternative approach would be to create a more optimal data structure. You can even get this to work with your original data structure by adding a $watch - something like:

$scope.$watch('items',function(){
  var itemDateMap = {};

  for(var i=0; i<$scope.items.length; i++){
    var item = $scope.items[i], key = item.date;
    if(!itemDateMap[key]){
      itemDateMap[key] = [];
    }
    itemDateMap[key].push(item);
  }

  $scope.itemDateMap=itemDateMap;


},true);

Works with this markup:

<div ng-repeat="(date,subItems) in itemDateMap">
<h3>{{date}}</h3>
<ul>
  <li ng-repeat="item in subItems">
    {{item.name}}
  </li>
</ul>  
</div>

Here is an example where you can add lots of random items.

shoma

When I have same needs like yours, I used Object instead of Array.

<div ng-repeat="item in data">
  <h1>{{item.date}}</h1>
  <ul ng-repeat="name in item.names">
    <li>{{name}}</li>
  </ul>
</div>

http://jsfiddle.net/shoma/DqDsE/1/

This question page would help you.

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!