问题
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;
}
}
}
});
回答1:
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.
回答2:
The Fiddle3
makes sense since it tries to hide itself and all variables are in its own isolated scope.
It will be more comparable to Fiddle1
if you want to implement something like when click on X, trigger the Toggle
button to hide sample
control. Because in Fiddle1
you actually wanted to figure out how to modify the value outside the isolated scope, rather than inside the scope created by the directive.
来源:https://stackoverflow.com/questions/18024809/why-does-two-way-binding-sometimes-work-without-using-a-dot-in-angular