Applications

Avoiding Duplicate HTML Elements with ng-bind and Ternary Operators

Here is a nice pattern for biding data to you HTML that is good to follow if you want to keep your HTML clean and simple.

 So you have a table that you are populating with values that you are getting form the server. Your table may look something like this:

1
And your code may look something like this:

 

The problem is that the value for Birth Year may come in as undefined from your API, maybe because some of the people listed in the table refused to give their birth age, maybe because they do not want others to find out how old they are, or maybe because they are 1000+ year old mythical creatures who want to keep the secrets of eternal youth to themselves. Who knows? Now, because of this, your table may look like this:

2

Did you notice that awkward empty space in the last row? Now your designer asks you to enter a symbol such as “-“ instead of blank spaces for ages that come in as undefined. Your first thought may be to write something like this:

That works. Hurray! But now our HTML is starting to look a bit busy. Wouldn’t be nicer and more readable to have only one line of HTML? A better solution is to use ng-bind to simplify our code:

Ahhh, much better. You are just doing the same job that Angular would have done for you by using the ng-bind property, and your code looks better. The expression

will simply evaluate to the string ‘-‘ when user.bYear is undefined.

But what happens if bYear does not come in as undefined value but with the string “NA” instead? The above solution wouldn’t work, but you can still keep your code clean by useing the ternary operators in your html:

This basically says: “is user.bYear equal to the string ‘NA’ ? If so display a ‘-‘; otherwise display the value of user.bYear.” So fresh and so clean clean.

Leave a Reply