[英]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. 该服务返回带引号的值“null”。 What is the best way of trying to do this?
尝试这样做的最佳方法是什么?
To do so, you can simply run your ng-if on your var. 为此,您只需在var上运行ng-if即可。
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. 如果你的userTest为null,则ng-if将为false,否则它将为true,并且此变量将是可见的。
Try to return
value: 尝试
return
值:
$scope.displayUsername = function () {
$scope.userTest = authService.getUsername();
return $scope.userTest;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.