How to use the actual use of ng-Cloak directive in AngularJs?

Anil Singh picture Anil Singh · Feb 14, 2015 · Viewed 42.8k times · Source
  1. What is the ng-cloak directive?
  2. Why do we use it?

Answer

Ben Diamant picture Ben Diamant · Feb 14, 2015

ng-cloak

From the docs:

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.

In brief words, you can use ng-cloak directive to prevent uncompiled elements from being displayed. Uncompiled element can be an element that hold and wait for incoming data:

<div ng-cloak>{{myvar}}</div>

if myvar controller still not compiled or the data is not populated ng-cloak prevent "{{myvar}}" from being displayed and will only display the div when the variable is compiled.

Follow this code example and check to results with and without ng-cloak:

<style>
    [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-    ng-cloak {
        display: none !important;
    }
</style>

<body ng-controller="MyController" ng-cloak>
    <h3>ngCloak Example</h3>
        <ol >
            <li ng-repeat="item in myData">
                {{item.title}}
            </li>
        </ol>
</body>


var myApp= angular.module("myApp",['ngResource']);

myApp.controller("MyController", ["$scope", "$resource","$timeout",
    function($scope,$resource,$timeout){
        $scope.myData =[];

        var youtubeVideoService = $resource("https://gdata.youtube.com/feeds/api/videos?q=googledevelopers&max-results=5&v=2&alt=jsonc&orderby=published");

        youtubeVideoService.get()
            .$promise.then(function(responseData) {

        angular.forEach(responseData.data.items,
            function(aSingleRow){
                console.log(aSingleRow);
                $scope.myData.push({
                    "title":aSingleRow.title
                }); 
            });
        }); 
}]);