How can I change the template message depending on whether the variable is null or not?

I am using this post:

{{ qs.q.hint }}

      

How can I do this so that the display shows "Please choose correct answers" if qs.q.hint is null or ""?

+3


source to share


3 answers


Very simple with directives ng-show

or ng-hide

:

<span ng-hide="qs.q.hint">Please choose the correct answer</span>

      



If the expression pointed to qs.q.hint

is true (not null

, undefined

, 0

, false

or an empty string), it will hide the span. Reverse can be achieved with ng-show

or using the unary !

boolean operator .

+4


source


I recommend this:

{{ qs.q.hint || "Please choose the correct answers" }}

      

This is watching $scope.qs.q.hint

and once it is not undefined or null the message will change



It is also the shortest. You can also bind multiple values ​​to such an expression, and the first valid value will be returned. For example, you might have qs.q.hint return a string hint when the user clicks "show me a hint". But you might need another hypothetical function to return an explanation if they picked the wrong answer. Then you could do this if you had a function selectedValInfo()

that returned undefined, false, 0 or null until a value is fetched, then some information is returned. This will be canceled when qs.q.hint becomes true.

{{ qs.q.hint || qs.q.selectedValInfo() || "Please choose the correct answers" }}

      

+1


source


Just use angular ng-if

just like normalif condition

  <span ng-if="qs.q.hint===null || qs.q.hint===''">Please choose the correct answer</span>

  <span ng-if="qs.q.hint!==null || qs.q.hint!==''">qs.q.hint</span>

      

0


source







All Articles