[英]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.