There's actually two separate problems that can cause the flicker issue and you could be facing either one or both of these.
Problem 1: ng-cloak is applied too late
This issue is solved as descibed in many of the answers on this page is to make sure AngularJS is loaded in the head. See ngCloak doc:
For the best result, angular.js script must be loaded in the head
section of the html file; alternatively, the css rule (above) must be
included in the external stylesheet of the application.
Problem 2: ng-cloak is removed too soon
This issue is most likely to occur when you have a lot of CSS on your page with rules cascading over one another and the deeper layers of CSS flash up before the top layer is applied.
The jQuery solutions in answers involving adding style="display:none"
to your element do solve this issue so long as the style is removed late enough (in fact these solutions solve both problems). However, if you prefer not to add styles directly to your HTML you can achieve the same results using ng-show
.
Starting with the example from the question:
<ul ng-show="foo != null" ng-cloak>..</ul>
Add an additional ng-show rule to your element:
<ul ng-show="isPageFullyLoaded && (foo != null)" ng-cloak>..</ul>
(You need to keep ng-cloak
to avoid problem 1).
Then in your app.run set isPageFullyLoaded
:
app.run(['$rootScope', function ($rootScope) {
$rootScope.$safeApply = function (fn) {
$rootScope.isPageFullyLoaded = true;
}
}]);
Be aware that depending on exactly what you're doing, app.run may or may not be the best place to set isPageFullyLoaded
. The important thing is to make sure that isPageFullyLoaded
gets set to true after whatever it is you don't want to flicker is ready to be revealed to the user.
It sounds like Problem 1 is the problem the OP is hitting, but others are finding that solution does not work or only partially works because they are hitting Problem 2 instead or as well.
Important Note: Be sure to apply solutions to both ng-cloak being applied too late AND removed to soon. Solving only one of these problems may not relieve the symptoms.