在角度分量中使用'require' [英] Using 'require' in angular component

查看:179
本文介绍了在角度分量中使用'require'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. Which is true?

推荐答案

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

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中显示组件和指令应如何交互的方式

An example from the guide shows the way how the components and directives should interact in 1.5 without the aid from link.

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

When require object and bindToController are used together, required controller instances are assigned to current controller as properties.

因为在指令链接期间发生这种情况,所需的控制器在控制器构造函数中不可用,这就是为什么 $ onInit 魔术方法就在那里。如果存在,请在添加所需控制器后立即执行 a>到

Because this happens during directive linking, the required controllers aren't available in controller constructor, that's why $onInit magic method is there. If it exists, it is executed right after adding required controllers to 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);
      };
    }
  }
});

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和<$ c中互换使用$ c> component 是一个简洁的。

declaration styles are on a par under the hood and can be used interchangeably in 1.5, and component is a concise one.

这篇关于在角度分量中使用'require'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆