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
.
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.
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.
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) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With