我不确定如何描述我遇到的问题,或者即使它是一个问题。我想我很难理解 Angular 指令是如何工作的。欢迎任何关于最佳实践的建议和/或意见。
我的控制器的 $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>
....
我可以在这个 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>
所以,我的问题是:
- 我是否正确地考虑了这个问题?我是否应该修改我的数据结构以按日期对其进行分组,然后只对每个单独的日期进行 ng-repeat?
- 如果有办法用我现有的数据结构做到这一点,我是否需要在生日男孩/ng-repeat 指令之外修改 DOM?
- 有没有办法将 ng-repeat 指令包装成自定义的东西 - 我已经开始研究 compile 函数但是,只是不确定......
谢谢!