Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent scope from child controller when using "controller As" and IIFE?

I'm using "controller as" syntax and I have each controller in a separate file wrapped in an IIFE, as recommended in John Papa's AngularJS Style Guide.

Is there a way to access properties declared in the scope of the parent controller from the child controller?

I can access them in the view by doing {{parent.variableOfParent}}, but don't know how to do that from the JS of the child controller.

Plnkr

P.S. It may be good to create a tag for the style guide as there are quite a few questions about it.

like image 205
Nelu Avatar asked Dec 01 '14 11:12

Nelu


1 Answers

You're in essence talking about sharing data between controllers. Well according to me [and by others too ;)], the best way to do so is using services..

  1. Create a service.

  2. Inject the service in both your controllers and save the service reference in the scope of the controllers.

  3. You can now access the data in both view and controllers.

yourApp.service("sharedService", function() {
    this.data = "123";
})

yourApp.controller("parentController", function(sharedService) {
    $scope.sharedService = sharedService;
});

yourApp.controller("childController", function(sharedService) {
    $scope.sharedService = sharedService;
});

Now anything that you want to "share" between the two controllers, can be placed inside the service.

Also, in the html, you can use the same service reference to access the data :

e.g.

    <div ng-app='app' ng-controller='ParentCtrl as parent'>
      
      <div ng-controller='ChildCtrl as child'>
        {{parent.sharedService.data}}<br> <!-- both will print the same value -->
        {{child.sharedService.data}}<br> <!-- both will print the same value -->
      </div>
    </div>
like image 50
Manish Kr. Shukla Avatar answered Sep 28 '22 19:09

Manish Kr. Shukla