为什么有时在 Angular 中不使用点就可以进行双向绑定? [英] Why does two way binding sometimes work without using a dot in Angular?
问题描述
考虑这个小提琴:Fiddle 1 当您选择一个日期时,您会注意到上面的文字没有更新.这是因为我必须在我的列表中使用一个对象,如下所示:Fiddle 2(简化版).
但是,另一方面,这确实有效,没有点:Fiddle 3
有人可以解释小提琴 1 和小提琴 3 之间的区别吗?我读过原型继承(unerstanding scopes),但我不知道不理解这种行为.
小提琴 3:
HTML:
你好,{{name}}!<button ng-click="visible = !visible">切换</button><div ng-show="可见">部分内容<samplevisible="visible"></sample>
Javascript:
var myApp = angular.module('myApp',[]);函数 MyCtrl($scope) {$scope.name = '超级英雄';$scope.visible = true;}myApp.directive("sample", function(){返回 {限制:'E',模板:'<span ng-click="hide()" style="cursor: pointer;">X</span>',范围:{可见:'='},链接:功能(范围,元素,属性){scope.hide = function(){控制台日志(范围.可见);scope.visible = false;}}}});
如果您的指令创建了一个隔离作用域(并且没有中间作用域),并且它使用 =
进行双向数据绑定,你不需要使用对象属性 –也就是说,你不需要一个点"来让它工作.
在 Fiddle 1 和 2 中,ng-repeat 正在创建一个中间(子)作用域,该作用域原型继承自 MyCtrl 作用域.在这种情况下,您需要使用对象属性.
Consider this fiddle: Fiddle 1 When you select a date, you will notice that the text above it is not updating. This is because I had to use an object in my list, like this: Fiddle 2 (simplified).
But, on the other hand, this does work, without a dot: Fiddle 3
Could someone explain what the difference is between fiddle 1 and fiddle 3? I've read about prototypical inheritance (unerstanding scopes), but I don't understand this behavior.
Fiddle 3:
HTML:
<div ng-controller="MyCtrl">
Hello, {{name}}!
<button ng-click="visible = !visible">Toggle</button>
<div ng-show="visible">
Some content
<sample visible="visible"></sample>
</div>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.visible = true;
}
myApp.directive("sample", function(){
return {
restrict: 'E',
template: '<span ng-click="hide()" style="cursor: pointer;">X</span>',
scope:{
visible: '='
},
link: function(scope, element, attributes){
scope.hide = function(){
console.log(scope.visible);
scope.visible = false;
}
}
}
});
If your directive creates an isolate scope (and there are no intermediate scopes), and it uses =
for two-way databinding, you don't need to use object properties – i.e., you don't need a "dot" to get it to work.
In Fiddle 1 and 2, ng-repeat is creating an intermediate (child) scope that prototypically inherits from the MyCtrl scope. In this case, you need to use object properties.
这篇关于为什么有时在 Angular 中不使用点就可以进行双向绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!