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

六月ゝ 毕业季﹏ 提交于 2019-12-08 09:40:00

问题


I have my HTML like this

  <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>

I want to write generalized method to check all my ng-include file are loaded.

After loading all file i need to make a server call.

Is there any way to check this in angular js?


回答1:


use the onload of each template and increment a counter. if the form contains only ng-include divs, use the beow code to get the count, or write a function to get the count of divs with ng-include.

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
}



回答2:


ng-include triggers a request that goes through the template cache. This is done async so No, angular cannot provide you with a trigger for when all templates done loading.

You can prefetch the templates to the cache and handle the event from there ...

For example,

// 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 !');
});
...


来源:https://stackoverflow.com/questions/25779304/how-to-add-ng-include-callback-to-multiple-ng-include-directives-in-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!