0

I have an issue, i would like to take your suggestion on this. I have used child controller inside parent controller div . e,g,

<div ng-controler="parent">
    <div ng-controler="child"></div>
</div>

And in the js file , I have used module.controller("Parent") syntax for defining controller. I am not using $scope in controler for storing variables but i am using var self = this; and have all the variables on self object. Now i want to use parent variables inside child controller. as i am not using scope so i am unable to use this syntax $scope.parent. variables in child controllers.

Can you please advise on this that how to use parent controller variable in child controller. Any help is appreciated.

1

1 Answer 1

-1

The answer is in the question. In the parent controller, add the following line:

$scope.parent = self;

Now in the child controller, since its scope inherits from the parent scope, you can use

$scope.parent.foo 

to access the foo attribute of the parent controller.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer.But i am not using $scope to store variables for the dom elements. i am storing it in a self variable using var self= this; so i cant use parent scope variable in child as i have not kept variable on scope.
I understand what you did. You initialized a local variable named self to this in the parent controller. What makes you think that will help you access the parent controller from the child? It won't.
It can be done but by below mentioned way.HTML <div ng-app ng-controller="ParentCtrl as pc"> <div ng-controller="ChildCtrl as cc"> <pre>{{cc.parentCities | json}}</pre> <pre>{{pc.cities | json}}</pre> </div> </div> JS function ParentCtrl() { var vm = this; vm.cities = ["NY", "Amsterdam", "Barcelona"]; } function ChildCtrl() { var vm = this; ParentCtrl.apply(vm, arguments); // Inherit parent control vm.parentCities = vm.cities; }. but i using different syntax for defining controller i.e. var a =module; module.controller('controller name').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.