AngularJS:ngRepeat和指令

5

我正在尝试制作一些可重复使用的倒计时小部件。对于静态内容,效果很好,但是当我尝试动态添加它们时,我的指令无法理解ngRepeat中的变量。

标记:

<div ng-repeat="cdn in countdowns" class="countdown" countdown-end="{{cdn}}">
  <p ng-hide="over">{{days}} jours {{hours}} heures {{minutes}} min {{seconds}} sec</p>
  <p ng-show="over">Done</p>
</div>

指令:

...
link: function(scope, elm, attrs) {
  scope.days = '1';
  ...
}
...

感谢回复。 http://jsfiddle.net/hFGb7/14/

不是答案,只是观察:作用域应该是 $scope。 - Nick Lewis
3
在文档中,“scope for the link function” 的范围。 - hjrshng
这就是你所说的!惯例是内置函数和变量以 $ 开头。 - abhaga
1
实际上,称其为作用域而不是 $scope 更有意义。当您使用 $scope 时,就是在使用依赖注入 - 当 Angular 根据变量名称查找依赖项时。 - Scott Silvi
http://angulartutorial.blogspot.in/2014/04/angular-ng-repeat-in-directive.html - Prashobh
@NickLewis,scope变量只是包含传递给链接函数的作用域的变量,他甚至可以将其命名为"apples"。这不是对$scope的实际引用。你可能想看看:https://egghead.io/lessons/angularjs-scope-vs-scope - buddyp450
1个回答

5
问题在于插值表达式在链接函数被调用的时候还未运行。因此,{{cdn}} 的值是不可用的。有几种处理方法:
  1. 您可以直接在链接函数中使用cdn,因为它在作用域中可用。但这将使指令依赖于作用域中是否存在cdn
  2. 获取使用插值的属性值的推荐方法是使用$observe。请查看此内容:http://jsfiddle.net/hFGb7/28/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接