Angular.js更复杂的条件循环 [英] Angular.js more complex conditional loops

查看:112
本文介绍了Angular.js更复杂的条件循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的目标是创建这个

<h3>11.4.2013</h3>
<ul>
 <li>entry 1</li>
 <li>entry 2</li> 
 <li>entry 3</li>
</ul>

<h3>10.4.2013</h3>
<ul>
 <li>entry 4</li>
 <li>entry 5</li> 
 <li>entry 6</li>
</ul>

[
    {
        "name": "entry1",
        "date": "11.4.2013"
    },
    {
        "name": "entry2",
        "date": "11.4.2013"
    },
    {
        "name": "entry3",
        "date": "11.4.2013"
    },
    {
        "name": "entry4",
        "date": "10.4.2013"
    },
    {
        "name": "entry5",
        "date": "10.4.2013"
    },
    {
        "name": "entry6",
        "date": "10.4.2013"
    }
]

问题是,NG-重复将不得不对,所以我不会永远将能够​​做到这一点使用NG重复,是这样吗?我发现这个 http://jsfiddle.net/mrajcok/CvKNc/ 例如马克Rajnoc,但它的还是pretty限制。

The problem is that ng-repeat would have to be on li so I wouldn't never be able to do this using ng-repeat, is that right? I found this http://jsfiddle.net/mrajcok/CvKNc/ example from Mark Rajnoc, but it's still pretty limiting..

还有什么其他选择,我有吗?写我自己NG重复样的指令?还是有另一种方式做到这一点没有书面方式吗?

What other choices do I have? Write my own ng-repeat like directive? Or is there another way to do it without writting one?

推荐答案

您可以编写自己的过滤器,过滤掉了独特的日期外NG重复,是这样的:

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;
  }
});

与下面的标记:

<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>

看一看该工作plnkr例如 - 或本< A HREF =htt​​p://plnkr.co/edit/81knnd8KeUdYcMPW9foa?p=$p$pview相对=nofollow>更新,例如使用添加项目

不过,如果你将有一个很大的项目(数百或上千)这个解决方案不是最优的。另一种方法是创建一个更优化的数据结构。你甚至可以得到这个与原来的数据结构工作通过添加$手表 - 是这样的:

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);

工程与此标记:

<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.

这篇关于Angular.js更复杂的条件循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆