Angularjs 指令隔离作用域不触发$watch
我有一个指令,它和它的控制器共享数据,我用一个隔离作用域来做 但是,当我从指令内部更新数据时,指令和控制器都不会使用$watch看到数据更改 下面是我尝试做的一个例子:Angularjs 指令隔离作用域不触发$watch,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我有一个指令,它和它的控制器共享数据,我用一个隔离作用域来做 但是,当我从指令内部更新数据时,指令和控制器都不会使用$watch看到数据更改 下面是我尝试做的一个例子: var app = angular.module('myApp', []); app.controller('myAppCtrl', function($scope) { $scope.buttonSettings = { val: 0 } $scope.$watch('buttonSettings.va
var app = angular.module('myApp', []);
app.controller('myAppCtrl', function($scope) {
$scope.buttonSettings = {
val: 0
}
$scope.$watch('buttonSettings.val', function(val) {
console.log('watchInController')
console.log(val)
});
});
app.directive('buttonTest', function() {
return {
restrict: 'E',
scope: {
buttonSettings: '='
},
template: '<button>{{buttonSettings.val}}</button>',
link: function(scope) {
var button = $('button');
console.log(scope.buttonSettings)
scope.$watch('buttonSettings.val', function(val) {
console.log('watchInDirective')
console.log(val)
});
button.bind('mouseover', function() {
scope.buttonSettings.val++;
console.log('mouseover')
console.log(scope.buttonSettings.val)
})
}
}
});
var-app=angular.module('myApp',[]);
app.controller('myAppCtrl',函数($scope){
$scope.buttonSettings={
瓦尔:0
}
$scope.$watch('buttonSettings.val',函数(val){
console.log('watchInControl')
console.log(val)
});
});
应用指令('buttonTest',函数(){
返回{
限制:'E',
范围:{
按钮设置:'='
},
模板:“{buttonSettings.val}}”,
链接:功能(范围){
变量按钮=$(“按钮”);
console.log(作用域按钮设置)
范围$watch('buttonSettings.val',函数(val){
console.log('watchInDirective')
console.log(val)
});
bind('mouseover',function(){
scope.buttonSettings.val++;
console.log('mouseover')
console.log(scope.buttonSettings.val)
})
}
}
});
以下是plunkr中的完整示例:
我做错了什么?首先,不应该这样使用jQuery。您可以使用元素参数将按钮注入指令,而不是使用jQuery选择按钮 其次,您需要使用$scope.$apply在指令和控制器中触发手表
app.directive('buttonTest', function() {
return {
scope: {
buttonSettings: '='
},
link: function(scope, element) {
element.bind('mouseover', function() {
scope.$apply(function() {
scope.buttonSettings.val++;
});
})
}
}
});
检查这项工作。halilb是正确的,您不应该使用jQuery来选择元素,而是使用Angular提供给您的指令的元素,并且需要使用
$scope.$apply
来注册Angular上下文之外发生的事件。然而,您根本不需要制定新的指令来解决您的问题。只需使用Angular的ngMouseover
指令即可。您可以将函数绑定到它,也可以直接将逻辑添加到它。这里有一个非常简单的例子
<div ng-init="foo = 1">Value: {{foo}}</div>
<button ng-mouseover="foo = foo+1">Mouse over this: {{foo}}</button>
我确实知道ngMouseover——我在示例中没有使用它,因为我需要一种简单的方法来证明我遇到的问题。
<div>Value: {{foo}}</div>
<button ng-mouseover="incrementFoo()">Mouse over this: {{foo}}</button>
$scope.foo = 1;
$scope.incrementFoo = function() {
++$scope.foo;
};