gpt4 book ai didi

javascript - 为什么 $timeout 在不同的 Controller 中调用 $scope 函数?

转载 作者:行者123 更新时间:2023-11-30 07:38:19 26 4
gpt4 key购买 nike

我有一个使用 $timeoutcurrent-time 指令,它似乎在单独的 Controller 中调用函数。我很困惑为什么会这样,我认为 Controller 包含自己的范围并且彼此隔离?,

基本上,myFunctioncurrentTime 指令 $timeout 发生时被调用。这有什么大不了的?这会不会给我带来麻烦?有人可以帮助我理解这种行为吗?这是一个 plunker这证明了我正在谈论的行为。

这是我的 HTML:

<html ng-app="myapp">

<head> <!-- using Angular version 1.2.0-rc3 --> </head>
<body>

<div ng-controller="TimeController">
<span current-time></span>
</div>

<div ng-controller="MyController">
<span class="grrr">{{myFunction()}}</span>
</div>

</body>
</html>

我的 Angular 代码:

var myapp = angular.module('myapp', []);

// just to show that I'm using my currentTime directive in separate controller.
// but it still happens if remove TimeController.
myapp.controller('TimeController', ['$scope', function($scope) {
console.log('entering TimeController');
}]);

myapp.controller('MyController', ['$scope', function($scope) {

$scope.myFunction = function() {
console.log('calling myFunction');
return 'myFunction was last called @ ' + new Date().toString();
};

}]);

// continuous update for time
myapp.directive('currentTime', ['$timeout', function($timeout) {

return function(scope,element,attrs) {
function updateTime() {
$timeout(function() {
element.text(new Date().toString());
updateTime();
}, 1000);
};
console.log('start clock');
updateTime();
};
}]);

最佳答案

TL:DR;

将指令更改为

    $timeout(function() {
element.text(new Date().toString());
updateTime();
}, 1000, false);

它不会触发你的 myFunction()

说来话长

当你这样做的时候

<span class="grrr">{{myFunction()}}</span>

您基本上是在告诉 Angular,跨度的内容应该始终等于调用 myFunction() 的结果。

现在,Angular 不知道你的函数依赖什么类型的变量来返回结果,所以每当有什么变化时,它需要再次调用该函数以查看它是否返回其他东西(这称为脏检查)。请记住这一点,一旦我们查看指令,这将很重要。

在指令中你每秒运行一次$timeout。这会触发一个 $digest 循环,这基本上是 Angular 检测事情是否发生变化的方式。在这样做的过程中,它正在检查所有范围,这意味着它还将调用您的 myFunction() 以查看指令是否影响了它。这就是它不断被调用的原因。

现在,如果你不想要这种行为,你可以绑定(bind)到一个变量而不是一个函数,或者如果你像我一样好奇,请转到 $timeout 的源代码。 .我想你可以看看 documentation也一样,但老实说,大多数 Angular 文档都不是很好,所以我通常会先寻找源代码。

有一个名为 invokeApply 的可选标志(甚至有文档记录),如果您将其设置为 false,则 $timeout 将不会触发脏检查。

关于javascript - 为什么 $timeout 在不同的 Controller 中调用 $scope 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524030/

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