今天,我在使用$ watch的AngularJS中遇到了一些非常奇怪的行为。我将代码简化为以下示例:
https://jsfiddle.net/yLeLuard/
此示例包含一个将跟踪state
变量的服务。伪指令用于将click事件绑定到state
通过服务更改变量的DOM 。
此示例中有两个问题:
main.html
<div ng-controller="main">
State: {{ api.isOpen | json }}
<div ng-click="" open>
<button>Open - Working fine</button>
</div>
<div ng-click="" close>
<button>Close - Works, but only on second click</button>
</div>
<div open>
<button>Open - Not Working</button>
</div>
<div close>
<button>Close - Not Working</button>
</div>
</div>
main.js
var myApp = angular.module('myApp', []);
myApp.controller('main', ['$scope', 'state', function($scope, state) {
$scope.api = state;
$scope.api.isOpen = false;
$scope.$watch('api.isOpen', function() {
console.log('state has changed');
});
}]);
myApp.directive('open', ['state', function(state) {
return {
restrict: 'A',
scope: {},
replace: true,
template: '<button>Open</button>',
link: function(scope, element) {
element.on('click', function() {
state.isOpen = true;
});
}
};
}]);
myApp.directive('close', ['state', function(state) {
return {
restrict: 'A',
scope: {},
replace: true,
template: '<button>Close</button>',
link: function(scope, element) {
element.on('click', function() {
state.isOpen = false;
});
}
};
}]);
myApp.service('state', function() {
return {
isOpen: null
};
});
那是因为您在上使用了本机事件侦听器click
。此事件是异步的,不在Angular摘要周期内,因此您需要手动摘要范围。
myApp.directive('open', ['state', function(state) {
return {
restrict: 'A',
scope: {},
link: function(scope, element) {
element.on('click', function() {
scope.$apply(function() {
state.isOpen = true;
});
});
}
};
}]);
固定小提琴:https : //jsfiddle.net/7h95ct1y/
我建议直接在ng-click中更改状态: ng-click="api.isOpen = true"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句