With the original way of defining controllers, access to the parent area was pretty trivial, since the content area of ββthe prototype inherits from its parent.
app.controller("parentCtrl", function($scope){ $scope.name = "Parent"; }) .controller("childCtrl", function($scope){ $scope.childName = "child of " + $scope.name; }); <div ng-controller="parentCtrl"> {{name}} <div ng-controller="childCtrl"> {{childName}} </div> </div>
The Controller-As approach seems to be recommended to declare the controller. But with Controller-As, the above approach no longer works.
Of course, I can access the parent scope using pc.name from the view:
<div ng-controller="parentCtrl as pc"> {{pc.name}} <div ng-controller="childCtrl as cc"> {{cc.childName}} </div> </div>
I have some problems with this (potential for spaghetti code), but this question is about accessing the parent area from the child controller.
The only way I see this is:
app.controller("parentCtrl", function(){ this.name = "parent"; }) .controller("childCtrl", function($scope){ $scope.pc.name = "child of " + $scope.name; // or $scope.$parent.pc.name = "child of " + $scope.name; // there no $scope.name // and no $scope.$parent.name });
So, now the child controller should know about " pc " - except that this should (in my opinion) be limited to the view. I do not think that the child controller should be aware that the view has decided to declare ng-controller="parentCtrl as pc" .
Q: What is the right approach?
EDIT:
Clarification: I do not want to inherit the parent controller. I am looking to inherit / modify a common area. Therefore, if I corrected the first example, I would have to do the following:
app.controller("parentCtrl", function($scope){ $scope.someObj = {prop: "not set"}; }) .controller("childCtrl", function($scope){ $scope.someObj.prop = "changed"; });
angularjs angularjs-scope angularjs-controller
New Dev Oct 30 '14 at 7:39 2014-10-30 07:39
source share