在角度组件中使用“require" [英] Using 'require' in angular component

查看:23
本文介绍了在角度组件中使用“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 中应该如何交互而没有来自 link 的帮助.

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

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

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

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

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 中互换使用,而 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天全站免登陆