How can I change the template message depending on whether the variable is null or not?
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 .
source to share
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" }}
source to share