分组ng-repeat和修改DOM外部指令

Grouping ng-repeat and modifying DOM outside directive

本文关键字:外部 指令 DOM 修改 ng-repeat 分组      更新时间:2023-09-26

我不确定如何描述我所遇到的问题,或者即使它是一个问题。我想我在理解Angular指令是如何工作的时候遇到了麻烦。欢迎就最佳做法提出任何建议和/或意见。

我有一个简单的数组对象在我的控制器的$作用域:

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

我可以用这个活塞实现类似的效果。

然而,在这里,我最终得到了一个稍微不同的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. 我对这个问题的思考是否正确?我是否应该修改数据结构,按日期分组,然后在每个日期上重复?
  2. 如果有一种方法可以做到这一点与我现有的数据结构,我需要修改外的DOM生日男孩/ng-repeat指令?
  3. 是否有办法将ng-repeat指令包装成自定义的东西-我已经开始研究编译函数,但是,只是不确定…

谢谢!

我将在控制器中按日期分组,然后对新的scope属性进行ng-repeat。这是我为一个类似的"分组"问题写的小提琴。您应该能够根据自己的代码调整它。我使用orderByFilter

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

,但你可能需要使用dateFilter或任何JavaScript代码,你可能有周围排序的dob的东西