MattDionis
MattDionis

Reputation: 3616

Stop ng-class from appearing until resolved

I'm using ng-class with the ternary operator to dynamically set a glyphicon. My problem is that whatever glyphicon is set in the else block appears for a second before the expression is resolved. Below is my HTML. header is simply the scope from my controller, and header.status is set in my controller after data is fetched from my API.

<i ng-class="header.status === 'single' ? 'glyphicon glyphicon-user pull-left' : 'glyphicon glyphicon-parents pull-left'"></i>

Note: I tried adding ng-cloak, but it made no difference.

Upvotes: 0

Views: 48

Answers (3)

Yoann
Yoann

Reputation: 446

You can do something like that :

<i ng-class="{'glyphicon':true, 'pull-left': true, 'glyphicon-user': header.status === 'single', 'glyphicon-parents': header.status && header.status !== 'single'}"></i>

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

If you wanted to hide the <i>, you could use ng-show:

<i ng-show="header.status" ng-class="header.status === 'single' ? 'glyphicon glyphicon-user pull-left' : 'glyphicon glyphicon-parents pull-left'"></i>

If you want to hide all classes until header.status is set, you could add another ternary:

<i ng-class="header.status ? (header.status === 'single' ? 'glyphicon glyphicon-user pull-left' : 'glyphicon glyphicon-parents pull-left') : ''"></i>

Or better yet, add a neat array to your controller:

$scope.statusArray = [];
dataService.getData().then(function() {
    $scope.statusArray.push("glyphicon", "pull-left");
    if(header.status === 'single') {
        $scope.statusArray.push("glyphicon-user");
    }
    else {
        $scope.statusArray.push("glyphicon-parents");
    }
});

And use that as your ng-class:

<i ng-class="statusArray"></i>

Sort of non-representative Fiddle :)

Upvotes: 1

Obi
Obi

Reputation: 3091

You need to add ng-cloak to the <i> and then add the css below to the style sheet of your page

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

Upvotes: 0

Related Questions