angularjs ng-cloak is not working when page load

13.3k views Asked by At

I am new to AngularJS and trying to fix the issue where some of the HTML code displays before ng-if condition gets evaluated. I am using ng-cloak as mentioned in many other stack over flow URLs but it still doesn't work for me. I am trying to load default image if actual image on URL is blank and when page loads, even if actual URL is there, it first blinks with default image and then loads the actual image because ng-cloak doesn't work correctly.

Please help.

I have below code and CSS etc.

Index.html

<!DOCTYPE>
<html>
<head>
    <meta charset="UTF-8">
    <base href="/">

    <title>Some App</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-resource.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
    <script src="https://code.angularjs.org/1.4.7/angular-sanitize.min.js"></script>

    <style type="text/css">
        [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
        display: none !important;
    }       
    </style>    
</head>
<body ng-app="app">
some code here
<div ng-view></div>
</body>
</html>

other.html

<div class="content">
    <div style="width: 100px; height: 40px;">

        <div ng-if="image.small">
            <img src="{image.small}}">
        </div>
        <div ng-if="!image.small" ng-cloak>
            <img src="image/default.png">
        </div>
</div>
6

There are 6 answers

7
Abhilash Augustine On

You can apply ng-cloak in your body tag. So, you whole body will be displayed only after angular's compilation.

<body ng-cloak ng-app="app">
..
</body>

This will solve your issue.

0
Oj G On

I did it always on my <html> tag. Like <html ng-app="someApp" ng-cloak>

0
Ruben On

the best solution is to have a loader while your app is waiting for the data. Instead of putting the ng-if on the flickering element, put in on the parent component and show a loader (it could like FB does a sort of mock of your UI).

2
Mittal Ashu On

    <div ng-if="image.small">
        <img src="{image.small}}">
    </div>
    <div ng-if="!image.small" class="ng-cloak">
        <img src="image/default.png">
    </div>

1
Pranita Yevle On

The timeout function will do what you want:

// timeout function will give some time for page load.
$timeout(function () {
  //your page load
  $("#panelTask").html(res);
});
0
krav On

I had to add :

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

to my css file for ng-cloak to work.

Like here :How to correctly use ng-cloak directive?