假设我们有以下指令:
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/