how to Access parent scope from child controller in angularjs

+1 vote
asked Dec 15, 2015 in Angular JS by jo (580 points)

I've set up my controllers using data-ng-controller="xyzController as vm"

I have a scenario with parent / child nested controllers. I have no problem accessing parent properties in the nested html by using $parent.vm.property, but I cannot figure out how to access the parent property from within my child controller.

I've tried injecting $scope and then using $scope.$parent.vm.property, but this isn't working?

Can anyone offer advice?

1 Answer

+1 vote
answered Dec 15, 2015 by Admin (1,860 points)
selected Dec 15, 2015 by jo
 
Best answer

If your HTML is like below you could do something like this:

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

Then you can access the parent scope as follows

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

If you want to access a parent controller from your view you have to do something like this:

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

See jsFiddle

Welcome to I Can Crack, where you can ask questions and receive answers from other members of the community.

68 questions

47 answers

3 comments

5,318 users

...