user3728375
user3728375

Reputation:

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

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?

Upvotes: 1

Views: 4404

Answers (2)

Sreekumar SH
Sreekumar SH

Reputation: 381

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
}

Upvotes: 5

haki
haki

Reputation: 9779

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

Upvotes: 2

Related Questions