Monday, 25 May 2015

AngularJS - preloading whole project / displaying loading image during AngularJS's bootstrap

It is very quick post but useful. I'll demonstrate how to display loading image before and during AngularJS's first load of the project - we do not want to use ng-cloack directive in this case. The trick is simple - the main goal is to divide project into two div elements - one for loading image and the other for the whole rest of the project. The first one will be displayed initially but the second one will be hidden using CSS. Because there is no AngularJS initially and we want to access the first div with the loading image to hide it when the app loads the only option is to define a directive restricted as a class. Consider following code:

html-template

   <div class="jumbotron vertical-center app-loading">  
     <div class="container-fluid">  
       <div class="row text-center">  
         <img src="~/Public/release/images/preloader.gif">  
       </div>  
       <div class="row text-center">  
         Application is loading. Please wait...  
       </div>  
     </div>  
   </div>  
   <div class="container-fluid" id="appContainer" style="display:none;">  
     <div class="col-xs-12" ng-view></div>  
   </div>  

app-loading directive

 define(['directives/directives', 'angular'], function (directives, angular) {  
   'use strict';  
   directives.directive("appLoading", [function () {  
     return ({  
       link: link,  
       restrict: "C"  
     });  
     function link(scope, element, attributes) {  
       element.remove();  
       scope = element = attributes = null;  
       angular.element('#appContainer').show();  
     }  
   }]);  
 });  

This solves our problem. Once AngularJS fully bootstraps on our application the appLoading directive is being executed, preloader hidden and contents of the app from ng-view displayed (could be a controller or something else).

No comments:

Post a Comment