Inheritance for scopes in AngularJS

In the area of ​​the parent controller, I defined selectedItem , which is set to 'x'. Then, in the child scope, I defined selectedItem using ngModel:

 <div ng-app> <div ng-controller="CtrlA"> <div ng-controller="CtrlB"> <select ng-model="selectedItem" ng-options="item for item in items"> </select> </div> </div> </div> function CtrlA($scope) { $scope.selectedItem = 'x'; $scope.items = ['x', 'y']; } function CtrlB($scope) {} 

When the page is loaded, selectedItem correctly set to "x" as expected. When I select "y", the selectedItem in the CtrlB $ area gives "y" as expected.

But when I check the scope of $scope.selectedItem in CtrlA (using AngularJS batarang), it gives an "x".

jsFiddle: http://jsfiddle.net/sudhh/GGKjp/2/

Preview page: http://fiddle.jshell.net/sudhh/GGKjp/2/show/light/ (for checking with angularjs batarang)

Why is the scope $scope.selectedItem in CtrlA not updated to 'y'? What is the explanation?

I prefer not to use events or rootScope to update selectedItem in the parent area (for training purposes).

+6
source share
2 answers

If you try to bind to a primitive declared in the parent area, then the selected area in the child area will effectively shadow the property with the same name in the parent area.

In this case, there are 3 options

  • define the objects in the parent for your model, then refer to the property of this object in the child: ref.selectedItem
  • use $ parent.selectedItem (not always possible, but easier than 1. where possible)
  • define a function in the parent scope and call it from the child, passing the primitive value to the parent (not always possible)

Read more about this at https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance

You can find the updated script using the first approach at http://jsfiddle.net/sudhh/XU2rP/1/

 function CtrlA($scope) { $scope.items = ['x', 'y']; $scope.ref = { selectedItem: 'x' }; } 
+7
source

I noticed in similar cases that AngularJS is not looking at selectedItem properly. The only way I found is to initialize selectedItem record from the items array. Try the following:

 function CtrlA($scope) { $scope.items = ['x', 'y']; $scope.selectedItem = $scope.items[0]; } 
0
source

All Articles