使用“controller As"时如何从子控制器访问父作用域和IIFE? [英] How to access parent scope from child controller when using "controller As" and IIFE?

查看:22
本文介绍了使用“controller As"时如何从子控制器访问父作用域和IIFE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 "controller as" 语法 并且我有每个控制器按照 John Papa 的 AngularJS 风格指南.

有没有办法从子控制器访问在父控制器范围内声明的属性?

我可以通过执行 {{parent.variableOfParent}} 在视图中访问它们,但不知道如何从子控制器的 JS 中执行此操作.

Plnkr

附言为风格指南创建一个标签可能会很好,因为有很多关于它的问题.

解决方案

您实际上是在讨论控制器之间的数据共享.根据我[以及其他人的看法;)],最好的方法是使用服务..

<块引用>

  1. 创建服务.

  2. 在您的控制器中注入服务并将服务引用保存在控制器的范围内.

  3. 您现在可以在视图和控制器中访问数据.

yourApp.service("sharedService", function() {this.data = "123";})yourApp.controller(parentController", function(sharedService) {$scope.sharedService = sharedService;});yourApp.controller(childController", function(sharedService) {$scope.sharedService = sharedService;});

现在你想分享"的任何东西两个控制器之间,可以放在服务里面.

此外,在 html 中,您可以使用相同的服务引用来访问数据:

例如

 

<div ng-controller='ChildCtrl as child'>{{parent.sharedService.data}}
<!-- 两者都将打印相同的值-->{{child.sharedService.data}}
<!-- 两者都将打印相同的值-->

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.

解决方案

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>

这篇关于使用“controller As"时如何从子控制器访问父作用域和IIFE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆