angularjs – 当使用“controller As”和IIFE时,如何从子控制器访问父作用域?

我正在使用 “controller as” syntax,我将每个控制器放在一个包含在 IIFE中的单独文件中,如John Papa的 AngularJS Style Guide中所推荐的那样.

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

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

Plnkr

附:为样式指南创建标记可能会很好,因为有很多关于它的问题.

你本质上是在谈论在控制器之间共享数据.那么根据我[以及其他人也是如此;)],最好的方法是使用服务..
  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;
});

现在,您希望在两个控制器之间“共享”的任何内容都可以放在服务中.

此外,在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>

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...