content inside ngSwitch not preserved?

121 views
Skip to first unread message

Eddie

unread,
May 9, 2012, 4:36:56 PM5/9/12
to ang...@googlegroups.com
http://jsfiddle.net/Gqmte/1/

I have an input inside one of the switch bind to a model. When you switch to different section then switch back to home , it appears that the model value resets.. Is this the expected behavior?

Pawel Kozlowski

unread,
May 9, 2012, 4:53:54 PM5/9/12
to ang...@googlegroups.com
Hi Eddie!
With the code you've provided - yes (although it might be confusing).
The thing is that ngSwitch is creating a new scope [1] (that is a
child scope of the one injected to your controller). So when you are
binding to the 'homeVal' you are actually creating a new value in the
scope created by ngSwitch. When the switch changes a scope is
destroyed and your binding goes away.

If you want to preserve the binding even when the switch changes
you've got at least 2 options:

1) Bind to the $parent scope instead, like in this jsFiddle:
http://jsfiddle.net/j6GSc/1/ Please note: <input type="text"
ng-model="$parent.homeVal">

2) Bind to a property of an object, here is the jsFiddle:
http://jsfiddle.net/j6GSc/2/

My preferred option would be (2) since it doesn't assume much about
scope's hierarchy.

Hope this helps,
Pawel

[1] http://docs.angularjs.org/api/angular.module.ng.$compileProvider.directive.ngSwitch

Eddie

unread,
May 9, 2012, 8:45:30 PM5/9/12
to ang...@googlegroups.com
I like the #2 approach. Let me add a comment to http://docs.angularjs.org/api/angular.module.ng.$compileProvider.directive.ngSwitch about this...
Reply all
Reply to author
Forward
0 new messages