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

风格不统一 提交于 2019-12-21 12:36:34

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/27227691/how-to-access-parent-scope-from-child-controller-when-using-controller-as-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!