如何在angular js中向多个ng include指令添加ng include回调

how to add ng-include callback to multiple ng-include directives in angular js

本文关键字:include ng 指令 回调 添加 angular js      更新时间:2023-09-26

我有这样的HTML

  <form ng-controller="testCtrl1">
    <div ng-include="'test/views/navigationbar.html'"></div>
    <div ng-include="'test/views/processnav.html'"></div>
    <div ng-include="'test/views/leftprocesstabs.html'"></div>
   </div>
</form>

我想写一个通用的方法来检查我所有的ng包含文件是否已加载。

加载完所有文件后,我需要进行服务器调用。

有没有办法在angular js中检查这个?

使用每个模板的onload并递增一个计数器。如果表单只包含ng-includediv,请使用beow代码来获取计数,或者编写一个函数来获取带有ng-includ的div的计数。

HTML

<form ng-controller="testCtrl1" id="includes">
    <div ng-include="'test/views/navigationbar.html'"  onload="load()"></div>
    <div ng-include="'test/views/processnav.html'" onload="load()"></div>
    <div ng-include="'test/views/leftprocesstabs.html'" onload="load()"></div>
   </div>
</form>

Javascript

var templates = 0;
var length = $("#includes > div").length; 
$scope.load = function(){
    templates++;
    if(templates >= length){
        onLoadComplete()
    }
}
function onLoadComplete(){
    // all templates are loaded
}

ng-include触发一个通过模板缓存的请求。这是异步完成的,所以不,angular不能在所有模板完成加载时为您提供触发器。

您可以将模板预取到缓存中,并从中处理事件。。。

例如,

// inject $q, $http, $templateCache to your controller 
...
var promises = [];
promises.push($http.get('test/views/navigationbar.html',{ cache : $templateCache }));
promises.push($http.get('test/views/processnav.html',{ cache : $templateCache }));
promises.push($http.get('test/views/leftprocesstabs.html',{ cache : $templateCache }));
$q.all(promises, function (data) { 
 console.log('All templates are loaded into the cache !');
});
...