angular/angular.js

ng-if breaks correct checkbox behavior...

mramosch opened this issue · 2 comments

The following code behaves absolutely correctly! It toggles the text’s color from blue to red via the checkbox and it shows the true/false state as the text.

<input type='checkbox' ng-init='checkStatus=false' ng-model='checkStatus'>
<span ng-if='checkStatus' style='color:red'> {{checkStatus}} </span>
<span ng-if='!checkStatus' style='color:blue' > {{checkStatus}} </span>

However, from the moment you introduce any ng-if=‘vm.isAllowed’ into the input tag, the checkbox does appear, depending on the ng-if value, however stops changing the color of the text, and, in a case like above where (for demonstration purpose) the actual text is the {{checkStatus}} ng-model variable, it does not show the text true/false anymore. Although the checkbox visually keeps toggling as expected.

<input type='checkbox' ng-if=‘vm.isAllowed’ ng-init='checkStatus=false' ng-model='checkStatus'>

If I, for further investigation, simply set ng-if=‘false’ obviously the checkbox will not get displayed at all, as expected.

<input type='checkbox' ng-if=‘false’ ng-init='checkStatus=false' ng-model='checkStatus'>

If I set ng-if=‘true’ the checkbox will show up as expected, however having lost its ability to toggle the text from blue to red, despite of showing the correct toggle on/off checkmark in the checkbox.

<input type='checkbox' ng-if=‘false’ ng-init='checkStatus=false' ng-model='checkStatus'>

I am expecting the true/false condition of an ‘ng-if’ (that got added to an input element) to be responsible for the appearing (or not) of the input element (checkbox), but not to change any already correctly working behavior of the checkbox - that it definitely has when the ng-if is omitted.

https://www.w3schools.com/code/tryit.asp?filename=GM32OE7PT48W

———

ngIf creates a new scope. I'd suggest using a Component and not accessing scope directly.

As @Splaktar said, this behavior is caused by the new scope created by ngIf (and the fact that Angular scopes use prototypal inheritance). See #16984 (and #16984 (comment) in particular) for more info.