LIVE DEMOAngularJS指令:为什么观察者没有被触发?
考虑以下两条指令:
JS:
angular.module("Directives", []).directive("action", function($compile) {
return {
restrict: 'A',
scope: {
action: '='
},
link: function(scope, element) {
scope.showDialog = false;
var template = "<span dialog='showDialog'>Dialog</span>";
element.append($compile(template)(scope)).on('click', function() {
console.log("Setting showDialog to true");
scope.showDialog = true;
});
}
};
}).directive("dialog", function() {
return {
restrict: 'A',
scope: {
dialog: '='
},
link: function(scope, element) {
element.hide();
scope.$watch('dialog', function(newValue) {
console.log("dialog changed to " + newValue); // Not called on button click
});
}
};
});
HTML:
<button action>Click Here</button>
你能解释一下为什么设置action
的showDialog
不会触发dialog
“看守人?
其实,当你点击按钮 - 指令'对话'中的'对话'不会改变 - 看起来不是绑定正确 - 也许是因为$ compile中的作用域与action-> link中的作用域不同?但我不知道如何解决这个问题。 –