angularjs - variable and it's parent scope inside ng-if -
according links read "unlike ng-show ng-if directive creates new scope. " confused below scenario. see demo
<div ng-if="true"> <div> visibility variable: {{showit}}<br> visibility variable: {{$parent.showit}} </div> <a href="" ng-show="!showit" ng-click="$parent.showit = true">show it</a><br> <a href="" ng-show="!$parent.showit" ng-click="$parent.showit = true">show it</a> <div ng-show="showit"> dynamically-shown div. <a href="" ng-click="hideit()">hide it</a> </div> </div>
in above example both {{showit}} , {{$parent.showit}} evaluate same value , ng-sho evaluate same values. in ng-click if dont specify parent give unexpected result ng-if creates child scope. checked while using ng-model parent scope needs used. why {{showit}} , {{$parent.showit}} evaluate same?
what care should take when using ng-if?
ng-if
create new scope, not isolate scope, inherits prototypically parent.
however, caveat of prototypal inheritance setting primitive value on child scope shadows value on parent scope, why need explicitly set $parent.showit
rather showit
in ng-click
.
here fiddle demonstrating issue: https://jsfiddle.net/sxkzzjfp/
example 1: child.showit
refers parent.showit
. try clicking "toggle parent" few times, , see values in sync. executing showit = !showit
causes child , parent values become decoupled, since child value shadows parent value.
example 2: workaround recommended angular. instead of setting primitive values directly on scope, set them on object instead. executing config.show = true
first looks prototype chain config
object on parent scope, , sets property of object. in example, child , parent values in sync.
Comments
Post a Comment