Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i inherit a parent controller's variables?

Tags:

angularjs

Here is my code:

function ParentCtrl($scope) { $scope.people = ["Tom", "Dick", "Harry"]; $scope.count = $scope.people.length; }  function ChildCtrl($scope) { $scope.parentpeople = ParentCtrl.people //this is what I would like to do ideally } 

I am nesting one angular controller inside of another one. I would like to pass variables of the first controller to the second one. Does anyone know how to do this?

NOTE

I cannot do something like

ChildCtrl.prototype = new ParentCtrl(); 

because I will overwrite the people property of the ChildCtrl.

like image 294
dopatraman Avatar asked Aug 17 '12 14:08

dopatraman


People also ask

How does a parent $scope relate to a child scope?

Angular scopes include a variable called $parent (i.e. $scope. $parent ) that refer to the parent scope of a controller. If a controller is at the root of the application, the parent would be the root scope ( $rootScope ). Child controllers can therefore modify the parent scope since they access to it.

How do you access child controller scope in parent controller?

In a nutshell: You cannot access child scopes from a parent scope. Your solutions: Define properties in parents and access them from children (read the link above) Use a service to share state.


2 Answers

By default, child scopes prototypically inherit from the parent scope (see Scope), so you already have access to the parent controller's $scope properties in the child. To prove it:

function ChildCtrl($scope) {     alert($scope.people) } 
like image 122
Mark Rajcok Avatar answered Sep 25 '22 04:09

Mark Rajcok


You're getting things wrong. You are mixing controller inheritance with scope inheritance, and they are different and loosly coupled in AngularJS.

What you actually want is:

function ParentCtrl($scope) {     $scope.people = ["Tom", "Dick", "Harry"];     $scope.count = $scope.people.length; }  function ChildCtrl($scope) {     $scope.parentpeople = $scope.$parent.people; } 

And it will work for the case:

<div ng-controller="ParentCtrl">     <div ng-controller="ChildCtrl">     </div> </div> 

But as Mark and ganaraj noticed above, this has no sense, as you can access your property of $scope.people from both ParentCtrl and ChildCtrl.

If you want to inherit controllers from each other, you need to use prototype inheritance of controller functions themselves.

like image 38
kstep Avatar answered Sep 22 '22 04:09

kstep