Prevent displaying un-compiled html template during loading in the web browser using directive ngCloak

Views: 1062
Comments: 2
Like/Unlike: 3
Posted On: 09-Jul-2017 10:27 

Share:   fb twitter linkedin
indrada...
116 Points
14 Posts
Introduction
When we work with the large web application in angularjs sometimes we see {{}} expression until the application page loaded. Here we can term it as un-compiled template loading. The directive ngCloak stops such flickering issue in AngularJS.
 
Detail
The ngCloak directive is used to prevent displaying un-compiled html template while loading in the browser. Mainly this directive removes the undesirable flicker effect caused by the html template compiled and display.
 
The directive can be applied to the <body> element, but the preferable location is to apply multiple ngCloak directives to small portions of the page to permit progressive rendering of the browser view.
 
ngCloak works in cooperation with the following css rule embedded within angular.js and angular.min.js.
 
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}​
 
 
When this css rule is loaded, all html elements (including their children) that are tagged with the ngCloak directive are hidden. When AngularJS finds this directive during the compilation of the template it removes the ngCloak element attribute, making the compiled element visible in the browser.
 
Note: For the best result, the angular.js script must be loaded in the head section of the html document.
 
Example
 
<!DOCTYPE html>  
<html>  
  
<head>  
    <title>ngClock directive in AngularJS to prevent showing un-compiled template</title>  
    <script src="angular.js"></script>  
</head>  
  
<body ng-app="app" ng-cloak>  
    <h4>ngClock Example</h4>  
    <div ng-controller="HomeController"> {{TestMeData}} </div>  
    <script>  
    var app = angular.module("app", []);  
    app.controller("HomeController", function($scope, $http)  
    {  
        $scope.init = function()  
        {  
            $http.get("dummyURL").then(function(result)  
            {  
                $scope.TestMeData = "Success";  
            }, function(error)  
            {  
                $scope.TestMeData = "Fail";  
            });  
        }  
        $scope.init();  
    });  
    </script>  
</body>  
  
</html>​
 
 
Conclusion
The ngCloak is very useful to prevent unwanted flickering. Hope this article will be helpful.
2 Comments
great..

Rahul Maurya
19-Nov-2017 at 06:11
Good catch

kikme
15-Jun-2018 at 05:02
 Log In to Chat