【发布时间】:2013-03-18 14:02:14
【问题描述】:
我不确定如何描述我遇到的问题,或者即使它是一个问题。我想我很难理解 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>
....
我可以实现接近这个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>
所以,我的问题是:
- 我是否正确地考虑了这个问题?我是否应该修改我的数据结构以按日期对其进行分组,然后只对每个单独的日期进行 ng-repeat?
- 如果有办法使用我现有的数据结构执行此操作,我是否需要在生日男孩/ng-repeat 指令之外修改 DOM?
- 有没有办法将 ng-repeat 指令包装到自定义的东西中 - 我已经开始研究 compile 函数,但只是不确定...
谢谢!
【问题讨论】:
-
遵守KISS原则并在控制器中分组(在
birthdays上使用$watch表达式)。 -
谢谢@stewie。有道理,出于某种原因,我想我认为最好执行一个指令来处理它。最后,这可能是更快/更便宜的解决方案。
标签: javascript angularjs angularjs-directive angularjs-ng-repeat ng-repeat