在 angular 组件中使用 'require'

Using 'require' in angular component

根据 the docs (specifically, the table comparing directives to components), angular components allow requiring other directives (or is it only components?). However, components do not have a link function, which could give access to the required controller. The source,与文档相反,似乎暗示在创建组件时不可能使用 'require'。哪个是真的?

引用的来源已过时。自 1.5.0 起,其他组件中的组件控制器 can be required(同样适用于指令)。

1.5 中的指南 shows the way how the components and directives should interact 中的示例,没有 link 的帮助。

require object and bindToController一起使用时,所需的控制器实例作为属性分配给当前控制器。

因为这发生在指令链接期间,所以所需的控制器在控制器构造函数中不可用,这就是 $onInit magic method is there. If it exists, it is executed right after adding required controllersthis 的原因。

两者都

app.directive('someDirective', function () {
  return {
    scope: {},
    bindToController: {},
    controllerAs: 'someDirective',
    require: {
      anotherDirective: '^anotherDirective'
    },
    controller: function ($scope) {
      console.log("You don't see me", this.anotherDirective);

      this.$onInit = function () {
        console.log("Now you do", this.anotherDirective);
      };
    }
  }
});

app.component('someComponent', {
  controllerAs: 'someComponent',
  require: {
    anotherDirective: '^anotherDirective'
  },
  controller: function ($scope) {
    console.log("You don't see me", this.anotherDirective);

    this.$onInit = function () {
      console.log("Now you do", this.anotherDirective);
    };
  }
});

声明样式在引擎盖下是同等的,可以在 1.5 中互换使用,component 是一种简洁的样式。