简体   繁体   English

在角度分量中使用'require'

[英]Using 'require' in angular component

According to 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 , contrary to documentation, seems to suggest that it is not possible to use 'require' when creating components. 与文档相反, 源代码似乎表明在创建组件时不可能使用'require'。 Which is true? 这是真的吗?

The cited source is outdated. 引用的来源已过时。 As of 1.5.0, component controllers can be required in other components (the same applies to directives). 从1.5.0开始,组件控制器可能在其他组件中需要 (同样适用于指令)。

An example from the guide shows the way how the components and directives should interact in 1.5 without the aid from link . 本指南中的一个示例显示了组件和指令在没有link辅助的情况下如何在1.5中进行交互的方式

When require object and bindToController are used together, required controller instances are assigned to current controller as properties. require对象和bindToController一起使用时,所需的控制器实例将作为属性分配给当前控制器。

Because this happens during directive linking, the required controllers aren't available in controller constructor, that's why $onInit magic method is there. 因为这在指令链接期间发生,所需的控制器在控制器构造函数中不可用,这就是为什么$onInit魔术方法存在的原因。 If it exists, it is executed right after adding required controllers to this . 如果它存在, 它需要添加控制器后立即执行this

Both

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);
      };
    }
  }
});

and

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);
    };
  }
});

declaration styles are on a par under the hood and can be used interchangeably in 1.5, and component is a concise one. 声明风格在引擎盖下可以使用,并且可以在1.5中互换使用,并且component是简洁的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM