gpt4 book ai didi

javascript - 需要知道,为什么需要使用$apply

转载 作者:行者123 更新时间:2023-11-30 05:36:31 24 4
gpt4 key购买 nike

我需要知道,为什么我们需要在这里使用 $apply,

var clock = angular.module('clock',[]); 
clock.controller('MyController', function($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
//updateClock() //why this will not work.
}, 1000);
updateClock();
});

Demo

我知道,当使用 $apply 时:

"The $apply() function executes an expression inside of the Angular context from outside of the Angular framework. For instance, if we implement a setTimeout() or are using a third-party library and we want the event to run inside the Angular context, we must use $apply()." Blockquote

但为什么我们需要在这种情况下使用(我的意思是在 jsfiddle 示例中),因为我在相同的上下文中并且没有使用任何 jQuery 代码或第三方库,

With Out $apply fiddle

调用了函数,但输出反射(reflect)在 View 中,为什么?

最佳答案

阅读以下手册。 :)
https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()

//根据评论更新
您需要使用 $interval服务。

关于javascript - 需要知道,为什么需要使用$apply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com