Reputation: 7681
I use ng-if
to display/hide some elements in page, as follows:
<span ng-if="user.name == ''||user.name ==null">Name:No Data</span>
<span ng-if="user.name != ''&& user.name !=null" ng-bind="'Name:' + user.name"></span>
but these two elements are shown no matter user.name
is set or not. I confirmed in the console of Chrome that the condition is true when running with debug mode.
It worked after I replaced ng-if
with ng-show
, I'm really confused with this.
Appreciated for any clarification. Thanks!
Update:
This is my $scope.user
:
var u = {
'loginId': mb,
'mobile': mb.substr(0,3 ) + "****" + mb.substr(7, 11),
'account': mb.substr(0,3 ) + "****" + mb.substr(7, 11),
'score': data.score,
'email': data.email,
'name': data.name,
'id': data.id
};
$scope.user = u;
Now I do have the value for user.name
, I tried the suggestions provided below, this is my test result.
Upvotes: 1
Views: 1965
Reputation: 27192
Make sure you have the latest Angular version, it wasn't available in early versions of ~v1.0.1
AngularJS added the ngIf directive in
1.1.5
Working Demo
var myApp = angular.module('myApp',[]);
myApp.controller("MyCtrl", function($scope) {
$scope.user = {
name: "Rohit"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<span ng-if="user.name == '' || user.name == null">Name:No Data</span>
<span ng-if="user.name != '' && user.name != null" ng-bind="'Name:' + user.name"></span>
</div>
Upvotes: 0
Reputation: 350
Just check your condition:
<span ng-if="user.name">Name:No Data</span>
<span ng-if="!user.name" ng-bind="'Name:' + user.name"></span>
Since JavaScript evaluates to false
when your user.name
is: null
, 0
, ""
(empty string), NaN
or just false
.
Works only if you are sure the variable was declared.
Upvotes: 0
Reputation: 9988
Your issue is with undefined.
Remember that null == undefined
but null !== undefined
.
So when the property is undefined, both the conditions are shown.
Your condition can be only ng-if="user.name"
or use strict equality ===
Upvotes: 0
Reputation: 2658
You are using ==
to check equality which succeeds even if the data is undefined or some other data like that. So use ===
which will do your job.
All the best.
Upvotes: 2
Reputation: 4401
This works well if user.name
is undefined
, null
or ""
function MyCtrl($scope) {
$scope.user = {
name: "xyz"
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app ng-controller="MyCtrl">
<span ng-if="!user.name">Name:No Data</span>
<span ng-if="user.name" ng-bind="'Name:' + user.name"></span>
</body>
Upvotes: 1