问题描述
angular 完成所有 watch 周期后,有没有办法在 angular 中调用自定义函数.
Is there any way to call custom function in angular after angular finishes all watch cycle.
要求我的控制器中有多个监视功能.现在我想在所有的watch函数都被angular执行完之后再执行一个函数
推荐答案
有几种方法可以在摘要完成后注册回调.
There are couple of ways to do register a callback once a digest is completed.
使用$$postDigest
:$scope.$$postDigest
在当前 $digest
循环完成后触发回调.
Using $$postDigest
:$scope.$$postDigest
fires a callback after the current $digest
cycle completed.
但是,在下一个摘要周期后,它只运行一次.要使其在每个摘要循环后运行,请与 $watch
一起运行.这是基于此处给出的代码示例
However this runs only once after the next digest cycle. To make it run after each digest cycle run it along with $watch
. This is based on the code sample given here
var hasRegistered = false;
$scope.$watch(function() {
if (hasRegistered) return;
hasRegistered = true;
$scope.$$postDigest(function() {
hasRegistered = false;
fn();
});
});
$watch
可以在摘要周期内多次触发,因此我们使用标志 hasRegistered
来防止 $$postDigest
回调被触发多次注册.注意:$$postDigest 不会触发另一个摘要循环.因此,对 $$postDigest
内的 $scope
的任何修改都不会反映在 dom 中.$$
表示这是angularjs中的私有函数,因此该函数不稳定,未来可能会发生变化.
The $watch
can get triggered multiple times during a digest cycle so we use a flag hasRegistered
to prevent $$postDigest
callback to be registered multiple times.Note: $$postDigest will not trigger another digest cycle. So any modifcation to $scope
inside $$postDigest
will not get reflected in the dom. $$
means this is a private function in angularjs, so the function is not stable and may change in the future.
使用$timeout
:
$timeout(function(){
console.log("Running after the digest cycle");
},0,false);
这会在当前摘要循环完成后运行.注意:第三个参数设置为 false 以防止另一个摘要循环触发器.
This runs after the current digest cycle is complete.Note: The third argument is set to false to prevent another digest cycle trigger.
这篇关于角度观察周期或摘要周期完成后如何调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!