angularjs - 使用 “controller As”和IIFE时如何从子 Controller 访问父作用域?

标签 angularjs angularjs-scope

我正在使用"controller as" syntax,并且按照约翰·帕帕(John Papa)的IIFE的建议,将每个 Controller 都包装在一个单独的文件中,并包装在AngularJS Style Guide中。

有没有办法从子 Controller 的父 Controller 的范围中声明访问属性?

我可以通过执行{{parent.variableOfParent}}在 View 中访问它们,但是不知道如何通过子 Controller 的JS来实现。

Plnkr

P.S.为样式指南创建标签可能会很好,因为对此存在很多疑问。

最佳答案

您实质上是在谈论 Controller 之间的数据共享。根据我(以及其他人;)的说法,最好的方法是使用服务。

  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;
});
现在,您想要在两个 Controller 之间“共享”的所有内容都可以放置在服务中。
另外,在html中,您可以使用相同的服务引用来访问数据:
例如
    <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>

关于angularjs - 使用 “controller As”和IIFE时如何从子 Controller 访问父作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27227691/

相关文章:

javascript - AngularJS 提供者和模型

AngularJS - 在 ng-repeat 中获取下一个兄弟作用域

javascript - Controller 连接到指令进行验证

angularjs - 无法在 angularjs 中的页面之间传递数据 - 包括 plunker

rest - AngularJS Controller /服务/http 通信

AngularJS - 将 v1.2.5 升级到 1.3 以使用一次绑定(bind)

AngularJS - 如何在多个值上设置 $watch

html - IE 9 不支持 $locationProvider.html5Mode

javascript - 语义 UI 模态对话框未正确关闭

javascript - AngularJS:不要在 DOM 更改时运行 ng-repeat