Search code examples
javascriptangularjsng-class

When removing a class using ngClass, how can I be sure that the element starts with the class?


A simple example of what I mean:

HTML:

<div ng-class="visibleClass"></div>

JS:

$scope.visibleClass = "invisible";
// Wait until the page loads
$scope.visibleClass = "";

CSS:

div.invisible {
  display: none;
}

Here the div should start out as invisible and become visible as the page loads.

What actually happens is that it is visible for a frame or two, and then becomes visible as the js file loads. This is especially apparent should a transition be in place, and the elements transits from its visible state to its invisible state when it should have just started in its invisible state.

How can I avoid this behaviour?

i.e, when I remove a class using ngClass, how can I be sure that the element starts off with that class?


Solution

  • It happens because it takes time for angular to bootstrap the app, the simplest solution would be to put a regular class attribute to the element with the value invisible.

    HTML

    <div ng-class="visibleClass" class="invisible"></div>