AngularJS conditionals in HTML Attribute

后端 未结 2 745
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 16:22

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:



        
相关标签:
2条回答
  • 2021-02-12 16:59

    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'}}"
    
    0 讨论(0)
  • 2021-02-12 17:00

    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.

    0 讨论(0)
提交回复
热议问题