Anil Singh Anil Singh - 5 months ago 20
AngularJS Question

Can one tell me the actual use of ng-Cloak directive in AngularJs?

Today I attended an interview, and the Interviewer asked me:


  1. What is
    ng-cloak
    directive?

  2. why we use it?



In AngularJs, I studied some tutorial, but I can't understand It.

Anyone can help me?

Answer

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
                }); 
            });
        }); 
}]);