Angular $watch 无法处理由指令更新的控制器变量
Angular $watch not working on controller variable updated by directive
我正在尝试监视控制器变量,该变量使用函数映射从指令更新。变量正在更新并登录到控制台,但观察它不工作。
代码片段:
index.html
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<test on-click="update()"></test>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
$scope.test = {
value: false
};
$scope.update = function() {
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
};
$scope.$watch('test', function(newVal){
console.log("Watch: " + newVal.value);
}, true);
});
myApp.directive('test', function($compile){
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
onClick: '&'
},
template: '<div ng-transclude=""></div>',
link: function(scope, element, attrs) {
var $buttonElem = $('<button>Test</button>').appendTo(element);
$buttonElem.click(function(){
scope.onClick();
});
}
}
});
Plunker Link 是:https://plnkr.co/edit/41WVLTNCE8GdoCdHHuFO?p=preview
问题是该指令使用不属于 AngularJS 的代码引发事件,而不是在其模板中使用 ng-click
。如果您不能修改该指令,则将您的事件处理程序包装在 $scope.$apply 中。
$scope.update = function() {
$scope.$apply(function(){
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
});
};
我正在尝试监视控制器变量,该变量使用函数映射从指令更新。变量正在更新并登录到控制台,但观察它不工作。
代码片段:
index.html
<body ng-app="myApp" ng-controller="myCtrl">
<div>
<test on-click="update()"></test>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
$scope.test = {
value: false
};
$scope.update = function() {
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
};
$scope.$watch('test', function(newVal){
console.log("Watch: " + newVal.value);
}, true);
});
myApp.directive('test', function($compile){
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
onClick: '&'
},
template: '<div ng-transclude=""></div>',
link: function(scope, element, attrs) {
var $buttonElem = $('<button>Test</button>').appendTo(element);
$buttonElem.click(function(){
scope.onClick();
});
}
}
});
Plunker Link 是:https://plnkr.co/edit/41WVLTNCE8GdoCdHHuFO?p=preview
问题是该指令使用不属于 AngularJS 的代码引发事件,而不是在其模板中使用 ng-click
。如果您不能修改该指令,则将您的事件处理程序包装在 $scope.$apply 中。
$scope.update = function() {
$scope.$apply(function(){
$scope.test.value = !$scope.test.value;
console.log("Update: " + $scope.test.value);
});
};