Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs: Change parent scope from controller within a ng-switch

So, I can change a model value from a child controller, but when the child controller is in ng-switch then it doesn't work, why? I created an example to demonstrate it.

One way to avoid this is to use the . in the model name, like bunnies.kills. Is this a bug or this is a feature ?

Using Angular 1.0.6

like image 600
Gacha Avatar asked May 22 '13 20:05

Gacha


2 Answers

Using your code structure, in your child controllers you would need to change:

$scope.$parent.kills++;

to

$scope.$parent.$parent.kills++;

Explanation: MainCtrl's scope is the parent scope of SimpleParentCtrl, but the grandparent of Step1Ctrl and Step2Ctrl. As some others pointed out, ng-switch creates its own scope, and then your Step1Ctrl and Step2Ctrl each created a child scope of the ng-switch.

Note: Each time the 1 or 2 button is clicked, both the ng-switch and it's currently matched child controller get a new scope.

Also: In case you happen to be looking in the Angular source and wondering how the ng-switch directive creates its own scope without a scope property, the answer is that it does so manually in its link method via scope.$new(). The directives ng-include, ng-switch, ng-repeat, and ng-view all create new scope this way, either in the link method or the compile method's returned link function.

Resources:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m

like image 120
Dan Avatar answered Sep 18 '22 18:09

Dan


ng-switch creates its own child scope, which is why @sh0ber's answer is one way to get it to work. In general, models should be referenced in controller scopes (hence reference objects), and not be not primitives. So using a . is a "best practice".

This is not a bug, but it is not a feature either. This is the way JavaScript prototypal inheritance works with primitives.

like image 30
Mark Rajcok Avatar answered Sep 18 '22 18:09

Mark Rajcok