Odd behaviour of ng-if in widget

68 views Asked by At

Can anyone explain this to me? I'm editing a widget and in the client HTML there's two ng-if statements (I've added the second, the first was already there).

<li>
<a ng-if="data.closedReopenPeriod==true" href="javascript&colon;void(0)" ng-click="$event.stopPropagation();buttonClicked('reopen')">${Reopen}</a></li>
<li>
<a ng-if="data.canEscalate=='true'" href="javascript&colon;void(0)" ng-click="$event.stopPropagation();buttonClicked('escalate')">${Escalate}</a></li>

Note the single quotes around the true in the second statement. As it's shown above it works.

If I change any of the single quotes, either add them from the first ng-if or remove them from the second, whichever statement is updated fails to work.

Can anyone tell me why?

My guess is the incoming data, but both variables are created in the same way in the server side script (I think - both are set to false at the top of the code).

(Side question, how does the "data" variable get populated on the server side script? Could it be that the first variable is already part of that object? I honestly don't know how it's created.)

1

There are 1 answers

2
Marek Vitek On

In short those variables are of different data type.

In your code you have two javascript statements. First one seems to be boolean that can be either true or false. Here various javascript conversions can be employed to cast closedReopenPeriod to boolean if it is not.

data.closedReopenPeriod==true

Second one is most likely string that can be "true" or "false" as a string, not boolean. Hence you need to wrap true with quotes to make it string literal.

data.canEscalate=='true'

To the confusion about not being able to add or remove quotes to either of these. Note that in javascript every non empty string is cast to true. See following code snippet. If statement will evaluate to true, because x is non empty string.

var x = 'false';
if (x) {
    gs.print('in if');
}

While you don't have to specify data types in JavaScript, it uses different data types internally. Comparing variables with different data type can cause unexpected behavior if you are unaware of conversion rules.

And one last thing. Variable can change its type during its lifetime. If you create it as a boolean and later assign string to it. It is string since the assignment. If it seems confusing to you, maybe read any info about type conversion.