为什么在本机setTimeout()函数中没有通知角?

时间:2021-07-11 20:58:32

Suppose i have an expression {{name}} , and in the controller i write something like

假设我有一个表达式{{name}},在控制器中我写了一些类似的东西。

$timeout(function(){
  $scope.name = "Stack Overflow";
},5000);

Then after 5 seconds the expression is evaluated to the string assigned. But if i write the same thing in native setTimeout(), then nothing happens Why? Any behind the scenes weird trick?

然后在5秒后,将表达式计算到指定的字符串。但是如果我在本机setTimeout()中编写相同的东西,那么为什么没有发生什么呢?在幕后有什么奇怪的把戏吗?

1 个解决方案

#1


2  

setTimeout: Calls a function or executes a code snippet after a specified delay (MDN).

setTimeout:在指定的延迟(MDN)之后调用函数或执行代码片段。

Angular is not aware of the changes that occur after any code is executed using setTimeout.

在使用setTimeout执行任何代码后,角度不知道发生的更改。

$timeout is Angular's wrapper for window.setTimeout. Behind the scenes this wrapper calls the $scope.$apply() method for you.

$timeout是用于window.setTimeout的角的包装器。在幕后,这个包装器调用$scope.$apply()方法。

You can achieve same behavior if you would call $scope.$apply() in setTimeout.

如果调用$scope,则可以实现相同的行为。

Edit:

编辑:

// #1
setTimeout(function() {
    $scope.name = 'Hola!';
}, 5000); 

// #2
setTimeout(function() {
    $scope.$apply(function () {
        $scope.name = 'Hola!';
    });
}, 5000);

// #3
$timeout(function() {
    $scope.name = 'Hola!';
}, 5000);

#1 - Angular unaware of update to $scope

#1 -不知道更新到$scope。

#2 - Angular knows that $scope.name has changed

#2 -斜角知道$scope.name已经更改。

#3 == #2

# 3 = = # 2

#1


2  

setTimeout: Calls a function or executes a code snippet after a specified delay (MDN).

setTimeout:在指定的延迟(MDN)之后调用函数或执行代码片段。

Angular is not aware of the changes that occur after any code is executed using setTimeout.

在使用setTimeout执行任何代码后,角度不知道发生的更改。

$timeout is Angular's wrapper for window.setTimeout. Behind the scenes this wrapper calls the $scope.$apply() method for you.

$timeout是用于window.setTimeout的角的包装器。在幕后,这个包装器调用$scope.$apply()方法。

You can achieve same behavior if you would call $scope.$apply() in setTimeout.

如果调用$scope,则可以实现相同的行为。

Edit:

编辑:

// #1
setTimeout(function() {
    $scope.name = 'Hola!';
}, 5000); 

// #2
setTimeout(function() {
    $scope.$apply(function () {
        $scope.name = 'Hola!';
    });
}, 5000);

// #3
$timeout(function() {
    $scope.name = 'Hola!';
}, 5000);

#1 - Angular unaware of update to $scope

#1 -不知道更新到$scope。

#2 - Angular knows that $scope.name has changed

#2 -斜角知道$scope.name已经更改。

#3 == #2

# 3 = = # 2