对ng-repeat进行分组并修改DOM外部指令

时间:2013-03-18 14:02:14

标签: javascript angularjs angularjs-directive angularjs-ng-repeat ng-repeat

我不确定如何描述我遇到的问题,或者即使这是一个问题。我想我无法绕过Angular Directives的工作方式。欢迎任何关于最佳实践的建议和/或意见。

我在控制器的$ scope中有一个简单的对象数组:

$scope.birthdays = [
      { name: "bob", dob:moment("09/20/1953"), cake: "vanilla"},
      { name: "michael", dob:moment("09/20/1953"), cake: "chocolate" },
      { name: "dave", dob:moment("09/20/1953"), cake: "chocolate" },
      { name: "chief", dob:moment("04/24/1977"), cake: "chocolate" },
      { name: "jerry", dob:moment("04/24/1977"), cake: "red velvet" },
      { name: "jerkface", dob:moment("04/24/1977"), cake: "i hate cake" },
      { name: "doug", dob:moment("05/10/1994"), cake: "marble" },
      { name: "jeff", dob:moment("05/10/1994"), cake: "vanilla" }
];

说我想从这个数据模型创建一个DOM结构:

<h1>Birthday: 09/20/1953</h1>
<div class="birthday">
   <h2>Name: bob</h2>
   <h3>Cake: vanilla</h3>
</div>
<div class="birthday">
   <h2>Name: michael</h2>
   <h3>Cake: chocolate</h3>
</div>
<div class="birthday">
   <h2>Name: dave</h2>
   <h3>Cake: chocolate</h3>
</div>
<h1>Birthday: 04/24/1977</h1>
<div class="birthday">
   <h2>Name: chief</h2>
   <h3>Cake: chocolate</h3>
</div>
....

我可以接近这个in this plunker

但是,我最终得到的DOM结构略有不同,我

<div ng-repeat="birthday in birthdays" birthday-boy="">
    <h3 ng-show="!birthdays[$index-1].dob.isSame(birthday.dob)" class="ng-binding" style="">
        September 20th, 1953
    </h3>
    <div class="ng-binding">
        Name: bob
    </div>
    <div class="ng-binding">
        Cake: vanilla
    </div>
</div>
<div ng-repeat="birthday in birthdays" birthday-boy="">
    <h3 ng-show="!birthdays[$index-1].dob.isSame(birthday.dob)" class="ng-binding" style="display: none;">
        September 20th, 1953
    </h3>
    <div class="ng-binding">
        Name: michael
    </div>
    <div class="ng-binding">
        Cake: chocolate
    </div>
</div>
<div ng-repeat="birthday in birthdays" birthday-boy="">
    <h3 ng-show="!birthdays[$index-1].dob.isSame(birthday.dob)" class="ng-binding" style="">
        April 24th, 1977
    </h3>
    <div class="ng-binding">
        Name: chief
    </div>
    <div class="ng-binding">
        Cake: chocolate
    </div>
</div>

所以,我的问题是:

  1. 我是否正确地考虑过这个问题?我应该修改我的数据结构,按日期对它进行分组,然后只对每个日期进行ng重复吗?
  2. 如果有办法用我现有的数据结构做到这一点,我是否需要在birthday-boy / ng-repeat指令之外修改DOM?
  3. 有没有办法将ng-repeat指令包装成自定义的东西 - 我已经开始研究编译函数但是,不确定......
  4. 谢谢!

1 个答案:

答案 0 :(得分:2)

我会在您的控制器中按日期分组,然后对该新范围属性进行ng-repeat。这是a fiddle我写的一个类似的“分组依据”问题。您应该能够根据代码进行调整。我使用了orderByFilter

$scope.sortedFriends = orderByFilter($scope.friends, '+age');

但您可能需要使用dateFilter或您可能拥有的任何JavaScript代码来对dob进行排序。