javascript - 一次性绑定(bind)以及指令的双向绑定(bind)和 ng-repeat

标签 javascript angularjs angular-directive

假设我们有以下指令:

app.directive('foo', function() {
  return {
    restrict: 'E',
    scope: { prop: '=' },
    template: '<h1>{{prop}}</h1>'
  };
});

Angular documentation表示可以使用一次性绑定(bind)和双向绑定(bind),如下所示:

<foo prop="::someProperty"></foo>

而且有效;如果 someProperty 稍后更改,foo 指令将不会知道它。

现在考虑这个标记:

<foo ng-repeat="item in items" prop="::item"></foo>

在这种情况下,如果 item 稍后更改,foo 将收到通知,就好像存在常规绑定(bind)一样。 :: 似乎没有任何实际效果(它确实阻止了创建额外的 watch ,我检查过自己)。我创建了 this plunker这说明了这两种情况。

我的问题是:这种行为是否正确?我希望它在两种情况下都保持一致。

最佳答案

我相信您的问题的答案是肯定的,这是正确的行为。当 items 中的 item 发生变化时,将创建模板的新实例,同时简单地删除旧模板。在您的例子中,创建了一个新的 foo 元素,因此 prop 属性值也是新的。这是来自 Angular ngRepeat文档:

When the contents of the collection change, ngRepeat makes the corresponding changes to the DOM:

  • When an item is added, a new instance of the template is added to the DOM.
  • When an item is removed, its template instance is removed from the DOM.
  • When items are reordered, their respective templates are reordered in the DOM.

它没有明确说明更新时会发生什么。但是,我相信新的会取代旧的而不是更新。

关于javascript - 一次性绑定(bind)以及指令的双向绑定(bind)和 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29567838/

相关文章:

javascript - url-to-image 渲染我尝试的每个 URL,除了我需要的 URL

javascript - 无法使用 AngularJS 指令更改 $templateCache 中的属性

javascript - 将数据传递给指令内部的 ng-repeat 指令

javascript - 如何将父div高度继承给它的 child

javascript - 当 angularjs 中的 ng-disabled 值为 true 时如何在复选框中显示 X 标记

javascript - d3.behavior.zoom 鼠标滚轮缩放中心动态偏移

javascript - UI-Grid 在页面加载时不会占用 100% 的宽度

Angular 自定义 ngIf 指令 'as' 语法

javascript - 如何在 Angular JS 中使用指令。在我的情况下不起作用,为什么?

javascript - Symfony2/Javascript 删除警报