我对这个课题进行了广泛的研究,但无论我做什么,我发现实现这个目标都极其困难。
我想在 AngularJS Web 应用程序中完全呈现所有元素时执行代码。我想我找到了建议使用路由器和视图的解决方案,但我无法在我的情况下使用它,因为它似乎需要某些配置。
当你有ng-repeat
和很多嵌套的directives
将根据各种条件生成 HTML/内容ng-if
,我注意到即使在文档就绪事件被触发或视图内容已加载后,HTML 渲染仍会继续,即$viewContentLoaded
事件被触发。
我最接近的想法是使用$watch
超过给定元素的子元素的长度directive
。每次$watch
执行完毕,计数器递增renderCount
。然后,在另一个计时器事件中,检查计数器是否renderCount
过去3-5秒没有变化,那么我们可以假设渲染已经完成。
监视子级并检查是否不再进行渲染的代码可能如下所示:
app.directive('whenRenderingDone', function($interval, $parse){
return {
link: function (scope, el, attrs) {
var renderingCount = 0;
function watchForChildren() {
scope.$watch(function(){
return $(':input', el).length;
}, function(newVal, oldVal){
if (newVal) {
renderingCount++;
}
})
}
watchForChildren();
//Check counter every 3 seconds, if no change since last time, this means rendering is done.
var checkRenderingDone = $interval(function(){
var lastCount = lastCount || -1;
if (lastCount === renderingCount) {
var func = $parse(attrs.whenRenderingDone);
$interval.cancel(checkRenderingDone);
func(scope);
}
lastCount = renderingCount || -1;
}, 3000);
}
}
});
我会尝试实施上述方法,如果您有反馈,请告诉我。
Tarek