在角度分量中使用'require'

Mac*_*ban 14 javascript angularjs angular-directive

根据文档(特别是将指令与组件进行比较的表),角度组件允许需要其他指令(或者它只是组件?).但是,组件没有链接功能,可以访问所需的控制器.与文档相反,源代码似乎表明在创建组件时不可能使用'require'.这是真的吗?

Est*_*ask 18

引用的来源已过时.从1.5.0开始,组件控制器可能在其他组件中需要(同样适用于指令).

本指南中的一个示例显示了组件和指令在没有辅助的情况下如何在1.5中进行交互的方式link.

require对象和bindToController一起使用时,所需的控制器实例将作为属性分配给当前控制器.

因为这在指令链接期间发生,所需的控制器在控制器构造函数中不可用,这就是$onInit魔术方法的原因.如果它存在,它需要添加控制器后立即执行this.

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);
      };
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

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);
    };
  }
});
Run Code Online (Sandbox Code Playgroud)

声明风格在引擎盖下可以在1.5中互换使用,并且component是简洁的.