任何人都可以解释一下,为什么当我点击我的元素时 vm.random
更新了元素内部,但是当我单击窗口 vm.random 时, View 层上没有更新(但 console.log
打印新值),尽管这两个事件触发相同的函数 vm.update()
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.5.9" data-semver="1.5.9" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script>
var app = angular.module('test', [])
.directive('testDir', function() {
return {
controllerAs: 'vm',
bindToController: true,
controller: function() {
var vm = this;
vm.random = Math.random();
window.onclick = function() {
vm.update();
};
vm.update = function() {
vm.random = Math.random();
console.log(vm.random);
};
},
template: '<div ng-click="vm.update()">Random number after click {{vm.random}}<input ng-model="vm.random"/></div>'
}
});
</script>
</head>
<body ng-app="test">
<h1>My directive</h1>
<test-dir></test-dir>
</body>
</html>
我应该在此代码段中更改什么才能在 window.onlick 更改 vm.random 后更新 vm.random ?
最佳答案
试试这个:
window.onclick = funciton(){
$scope.$apply(function(){
vm.update();
});
}
记住将 $scope 注入(inject)到你的 Controller 中
即使 vm.random
并不直接位于您的 $scope
上,Angular 仍然需要知道它已经发生了变化。手动调用 $scope.$apply
可以解决这个问题。
它与 ng-click
一起使用的原因是, Angular Directive(指令)会自动处理 $scope.$apply
ing
关于javascript - AngularJS 指令内的双向绑定(bind)适用于 ng-click,但不适用于 window.onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015937/