user3407039
user3407039

Reputation: 1335

Conditionally display an element with ng-if

I'm trying to display an expression on my webpage but only if the variable is existing.

So at the moment I have,

<ul class="nav navbar-nav navbar-right">
   <li ng-if="displayUsername()">{{userTest}}</li>
</ul>

and in my controller I have,

$scope.displayUsername = function () {
    $scope.userTest = authService.GetUsername();
}

The service returns a value of "null" with quotations. What is the best way of trying to do this?

Upvotes: 1

Views: 79

Answers (2)

Manwal
Manwal

Reputation: 23816

Try to return value:

$scope.displayUsername = function () {
    $scope.userTest = authService.getUsername();
    return $scope.userTest; 
}

Upvotes: 0

Pierre-Alexandre Moller
Pierre-Alexandre Moller

Reputation: 2354

To do so, you can simply run your ng-if on your var.

In your controller, you just declare the variable :

$scope.userTest = authService.getUsername();

And then, in your view :

<ul class="nav navbar-nav navbar-right">
   <li ng-if="userTest">{{userTest}}</li>
</ul>

If your userTest is null, ng-if will be false, else it will be true and this variable will be visible.

Upvotes: 3

Related Questions