AngularJS access parent scope from child controller

870    Asked by rachit_6798 in Devops , Asked on Jul 1, 2021
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 $scope parent property from within my child controller.
I've tried injecting $scope and then using $scope.$parent.vm.property, but this isn't working?


Answered by Manish Nagar

If you want to access $scope parent property from within your child controller. You can follow the below-mentioned steps:-

As you have defined cities in the parent controller your child controller will inherit all scope variables. But you do not have to call $parent.

See the code below:-

function ParentCtrl($scope) {

$scope.cities = ["NY","Amsterdam","Barcelona"];

}

function ChildCtrl($scope) {

$scope.parentCities = $scope.cities;

}



Your Answer

Interviews

Parent Categories