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

I use the “controller as” syntax , and I have each controller in a separate file enclosed in IIFE , as recommended in the John Papa AngularJS Style Guide .

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

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

Plnkr

PS It may be useful to create a tag for the style guide, as it has a lot of questions.

+6
source share
1 answer

You are essentially talking about the exchange of data between controllers. Well, according to me [and others too;)], the best way to do this is to use services.

  • Create a service.

  • Add the service to both controllers and save the service link in the controller area.

  • Now you can access the data in both the view and the 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 all that you want to "split" between two controllers can be placed inside the service.

In addition, in html you can use the same service link to access data:

eg.

  <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> 
+10
source

Source: https://habr.com/ru/post/978940/


All Articles