Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - ng-if check string empty value

Tags:

angularjs

it's a simple example:

<a ng-if="item.photo == ''" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a> <a ng-if="item.photo != ''" href="#/details/{{item.id}}"><img ng-src="/{{item.photo}}" class="img-responsive"></a> 

I see it always generates the item.photo != '' condition even if the value is empty. Why?

like image 593
Tony Avatar asked Dec 09 '14 13:12

Tony


People also ask

How to check empty string in AngularJS?

The Best Answer isphoto == '' or item. photo != '' . Like in JavaScript, an empty string will be evaluated as false.

How do you check if a string is empty in Ng if?

How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.

How do I check if a string is null or empty in typescript?

You can simply use typeof. It will check undefined, null, 0 and "" also.


2 Answers

You don't need to explicitly use qualifiers like item.photo == '' or item.photo != ''. Like in JavaScript, an empty string will be evaluated as false.

Your views will be much cleaner and readable as well.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>  <div ng-app init="item = {photo: ''}">     <div ng-if="item.photo"> show if photo is not empty</div>     <div ng-if="!item.photo"> show if photo is empty</div>         <input type=text ng-model="item.photo" placeholder="photo" />  </div

Updated to remove bug in Angular

like image 195
Martin Avatar answered Sep 19 '22 10:09

Martin


Probably your item.photo is undefined if you don't have a photo attribute on item in the first place and thus undefined != ''. But if you'd put some code to show how you provide values to item, it would help.

PS: Sorry to post this as an answer (I rather think it's more of a comment), but I don't have enough reputation yet.

like image 25
iulian Avatar answered Sep 18 '22 10:09

iulian