Tamara Tamara - 7 months ago 38
Javascript Question

Angular 1.4 - get parent controller property

I have the following HTML structure:

<div class="order-table-page" ng-controller="SummaryController as summaryCtrl">
<h3>Summary</h3>
<!-- Statutes summary information -->
...

<!--List of orders with selected statuses-->
<div ng-controller="OrderTableController as orderTableCtrl">
...
</div>

</div>


So, OrderTableController is a child of SummaryController. Now, in child controller I want to get access to the parent property. In parent class I define:

orderApp.controller('SummaryController', ['$location', 'ordersApi', function($location, ordersApi){

var ctrl = this;

ctrl.summary = [];
ctrl.test = 'test';

...

}]);


And in child controller I try to get "test" property:

orderApp.controller('OrderTableController', ['$location', '$scope', 'ordersApi', function($location, $scope, ordersApi){

var table = this;
table.orders = [];


console.log("Table orders 1");
console.log($scope.$parent.test);

...

}]);


I expect that $scope.$parent will contain SummaryController scope. But I'm not sure what it contains, because
$scope.$parent.test
is undefined and $scope.$parent has property named summaryCtrl.

My question is how to get parents property "test" form OrderTableController?

Answer

As your are using Controller As feature, it creates a property inside the $scope which will represent the controller itself.

So, in your SummaryController you have a test property. And in scope of this SummaryController it will be like $scope.summaryCtrl.test - because you defined it as SummaryController as summaryCtrl.

Therefore, you need to go in the same path from you child controller to get test property (it will be more elegant than working with $scope.$parent).

If you need to share some data between controllers, you can try to use shared services (as they are singletons) and use them in related controllers.