0

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?

Tamara
  • 2,910
  • 6
  • 44
  • 73

3 Answers3

2

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.

MaKCbIMKo
  • 2,800
  • 1
  • 19
  • 27
0

You simply have to add a refference in OrderTableController of SummaryController and you'll get everything from SummaryController in OrderTableController :)

Using $scope.$parent is not very elegant. Not neccesary wrong, but not elegant.

dpaul1994
  • 332
  • 3
  • 16
0

This may be because you are using this instead of $scope in the parent controller, if you do $scope.test='test' you could get it in the way you want $scope.$parent.test. See this fiddle: http://jsfiddle.net/f2zyvf17/

PD: You can see the difference of using $scope or this in this question: 'this' vs $scope in AngularJS controllers

Community
  • 1
  • 1
Sergio Fandino
  • 435
  • 3
  • 7