我正在尝试更新 h1
元素中的时钟时间。我试图通过设置间隔调用函数来更新时间,但我无法调用。我找到了 apply
的解决方案。
但我想了解这背后的逻辑。任何解释我不能打电话的原因以及为什么我们应该使用 apply 方法..?
这是我的作品:
angular.module('Book', [])
.controller('MyController', function ($scope) {
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
updateClock(); //not working when i call from here...?
//$scope.$apply(updateClock); //it works!
}, 1000);
updateClock(); //it works in first time.
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Book">
<div ng-controller='MyController'>
<input ng-model="name" type="text" placeholder="Your name">
<h1>Hello {{ clock }}</h1>
</div>
</div>
最佳答案
简而言之
Angular 在某些特定事件上运行 $digest 循环($digest 循环实际上负责双向数据绑定(bind)或脏检查)。该事件可能是在调用 $scope 函数时,$http 返回数据,$timeout, $interval 等。但如果你使用的不是这个,那么 angular 不知道有什么变化(比如 setTimeout,它是 javascript 函数)。所以我们明确需要告诉 angular,因为这个 angular 给了我们 $apply。
长期
引用此链接 http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
关于javascript - 为什么在 `controller`中直接调用 `AngularJs`的函数不可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389153/