0

I am binding following in my HTML.

<div>{{user.address[0].addressline1}}, {{user.address[0].addressline2}}, {{user.address[0].city}}, {{user.address[0].state}}, {{user.address[0].zipcode}}</div>

The issue is if addressline1 is null, it unnecessarily shows the , at first.

And also some other fields can be null

So How to display comma only if the value is not null?

2 Answers 2

1

Or as a matter of style, you can use a turnery operator to check for the value then format it

{{ !!user.address[0].addressline1 ? user.address[0].addressline1 + ', ' : ''}}

This could be made as filter to be more intuitive

angular.module('myapp', []).filter('trailIfTrue', [function(){
     return function(val, trail){
         return !!val ? val + trail : '';
     }
}]); 

usage:

{{ user.address[0].addressline1 | trailIfTrue:',' }}

here is a plunker

Sign up to request clarification or add additional context in comments.

1 Comment

I liked the filter option & used it...As it can be reused if i need it later...! Thanks..!
1

User separate span and ng-show so the span will be shown only if user.address[0].addressline1 is not null

<span ng-show="user.address[0].addressline1">{{user.address[0].addressline1}},</span>
<span ng-show="user.address[0].addressline2">{{user.address[0]. addressline2}},</span>
<span ng-show="user.address[0].city">{{user.address[0].city}},</span>
//...

You can use any expression into ng-show Eg:

user.address[0].addressline1 != null
myObj.myIntAttr > 0 && < 10
myObj.myBoolAttr == false
//...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.