[英]Angular.js two-way binding do not work when update the $scope in the controller of custom directive?
我在编写一组可以相互联系的指令时遇到了这个问题。
这是CodePen网址: http ://codepen.io/jennieji/pen/mDGuw
这是JS代码:
angular.module('app', [])
.directive('testDirective', function() {
return {
controller: function($scope){
$scope.now = 0;
this.update = function() {
$scope.now++;
};
},
link: function(scope) {
scope.$watch(function(){
return scope.now;
}, function(newVal, oldVal) {
element.append('<p>[LOG] $watch now:' + newVal + '</p>');
}, true);
scope.$watch('now', function(newVal, oldVal) {
element.append('<p>[LOG] $watch now:' + newVal + '</p>');
});
}
};
})
.directive('testUpdate', function() {
return {
require: '^testDirective',
link: function(scope, element, attr, ctrl) {
element.on('click', function(){
ctrl.update();
element.after('<p>[LOG] click now:' + scope.now + '</p>');
});
}
}
});
这是HTML:
<div ng-app="app">
<div test-directive>
<p>{{ now }}</p>
<button test-update>Update now</button>
</div>
<div>
由于您正在监听DOM click事件:
element.on('click', function(){
除非您$apply
否则您的范围更改将不会生效:
link: function(scope, element, attr, ctrl) {
element.on('click', function(){
scope.$apply(function() {
ctrl.update();
});
ctrl.update();
element.after('<p>[LOG] click now:' + scope.now + '</p>');
});
}
$apply
启动Angular $digest
循环,并进行双向绑定的脏检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.