Tamara Tamara - 1 year ago 123
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">
<!-- Statutes summary information -->

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


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");



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

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

Answer Source

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.