javascriptangularjsangularjs-scopeangularjs-controllerangularjs-ng-switch

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


Solution

  • 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