AngularJS conditionals in HTML Attribute

All we need is an easy explanation of the problem, so here it is.

How would you change an html attribute based on the model?

I’m trying to change an input’s placeholder text based on a length of an array:

<input placeholder="{{todos.length ? 'Insert todo' : 'Insert your first todo'}}" />

But that doesn’t seem to work…

JS Bin code example.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The ternary operator doesn’t seem to work in this case, instead of doing this

{{cond ? true : false}}

Change it to

{{ exp && true || false }}

So your placeholder attribute would look like this (I have shortened it for demonstration purposes)

placeholder="{{todos.length > 0 && 'Insert' || 'Insert first'}}"

Method 2

For anyone else who comes across this (like I just did via Google), it looks like Angular recently added support for the ternary operator in expressions. I just used it successfully in 1.2.16 to dynamically update a tooltip (title) attribute. It seems to have first appeared in the documentation for 1.2.17, although they still generally discourage its use:

From: AngularJS: Developer Guide: Expressions

Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the Angular philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply