从子组件访问最父控制器

Access the most parent controller from child component

我在我的应用程序中使用 angular 1.5 组件,这是我的结构:

<body ng-app ng-controller="appController as app">
    <div ui-view="home">
        <home-component>
            {{ app.user }}
        </home-component>
    </div>
</body> 

基本上,我将 ui-router 与 Angular 组件一起用于嵌套视图。

我知道,使用 controller as 语法,您可以访问父控制器,但出于某种原因我不能。 {{ app.user }}

未显示任何内容

现在我读到,组件的范围是隔离的,但我认为这只是意味着父组件不能访问子组件。

如果完全隔离,我将如何访问父控制器中的全局数据?

谢谢!

您可以使用 requires 在子组件中创建对它的引用。

这种语法基本上到处都能找到它:

require: {
      app: '^homeComponent'
    }

或者此语法将只查找一个组件作为父组件:

require: {
      app: '^^homeComponent'
    }

然后在子组件中您可以通过应用程序引用 homeComponent 属性。

您还可以通过在引用前面加上 ?喜欢:

  app: '?^^homeComponent'

使用require property访问父控制器和映射 绑定到子组件的控制器:

app.component("homeComponent", {
  require: {main: "^ngController"},
  template: 
    `<fieldset>
      <h3>home-component</h3>
      <p> $ctrl.main.user = {{$ctrl.main.user}}</p>
    </fieldSet>`
})

以上示例绑定到 ng-controller directive 的控制器。

来自文档:

Intercomponent Communication

Directives can require the controllers of other directives to enable communication between each other. This can be achieved in a component by providing an object mapping for the require property. The object keys specify the property names under which the required controllers (object values) will be bound to the requiring component's controller.

— AngularJS Developer Guide - Components (Intercomponent Communication)

The DEMO

angular.module("app",[])
.component("homeComponent", {
  require: {main: "^ngController"},
  template: 
    `<fieldset>
      <h3>home-component</h3>
      <p> $ctrl.main.user = {{$ctrl.main.user}}</p>
    </fieldSet>`
})
.controller("appController", function() {
  var main = this;
  main.user = "someUser";
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="appController as main">
      <h2>Main App</h2>
      <input ng-model="main.user" />
      <br><br>
      <home-component>
      </home-component>
  </body> 

如果一个指令是隔离的,最好通过参数传递你需要使用的任何值,否则为什么要隔离它?

<home-component user="app.user"></home-component>

.directive('homeComponent', function() {
  return {
    scope: { user: '=' },
    ...
  }
})

或者如果不需要在子指令中使用,您可以嵌入内容

<home-component>
    {{ app.user }}
</home-component>

.directive('homeComponent', function() {
  return {
    transclude: true,
    template: '<div><ng-transclude></ng-transclude></div>',
    ...
  }
})