0

I found a very helpful article on stackoverflow:

AngularJS access parent scope from child controller

The solution provided access the parent's scope, when the parent controller is global.

So for:

(function() { angular.module.controller('s').controller('ParentCtrl', function () { var vm = this; vm.cities = ["NY", "Amsterdam", "Barcelona"]; } }());

(function() {
    angular.module.controller('s').controller('ChildCtrl', function () {
    var vm = this;
ParentCtrl.apply(vm, arguments);

vm.parentCitiesByScope = $scope.pc.cities;
vm.parentCities = vm.cities;
} }());

How can you access the ParentCtrl's cities attribute, if we place an IIFE for each controller? Notice this ParentCtrl is no longer in the same scope as the child controller, so that we can't call the apply function.

If I have the controllers in separate files, how can I access the scope of the parent?

While having this as the html:

<div ng-app ng-controller="ParentCtrl as pc">
<div ng-controller="ChildCtrl as cc">
    <pre>{{cc.parentCities | json}}</pre>
    <pre>{{pc.cities | json}}</pre>
</div>

Community
  • 1
  • 1
user1413969
  • 1,261
  • 2
  • 13
  • 25
  • It's not clear exactly what you want to do. If you want to extract the parent properties using $scope, it's already in the answer and the previous well descriptive example. – Aviro Nov 07 '14 at 22:04

1 Answers1

0

Based on the modified question, I understand that you want to share information across multiple independent controllers. If this is something you are trying to achieve, you would use any of these.

  • Use $rootScope to share information. Since all controller scopes are inherited from $rootScope, you can use this method.
    However, it's not advisable to share methods/functions in the $rootScope and you should only put data.
  • Come up with a Service which does hold information in order to share the information. However, writing a service only to hold some data would not a best practice either. This would be beneficial if any outside communication / data modifications implemented inside the service.
    Sample Service
    angular.module('myApp')
    .service('MyService', function() {
       var cities = ["NY", "Amsterdam", "Barcelona"];
    
       this.getCities = function() {
          return cities;
       }
    }
    
    Service Usage
    angular.module('myApp')
    .controller('MyController', function($scope, MyService) {
       $scope.myCities = MyService.getCities();
    }
    

    Hope this helps.

  • Aviro
    • 2,125
    • 22
    • 28