javascript - 在 Angular 分量中使用 'require'

标签 javascript angularjs angular-directive

根据 the docs (具体来说,表格将指令与组件进行比较), Angular 组件允许需要其他指令(或者它只是组件?)。但是,组件没有链接功能,可以访问所需的 Controller 。 The source ,与文档相反,似乎暗示在创建组件时不可能使用“require”。哪个是真的?

最佳答案

引用的来源已过时。从 1.5.0 开始,组件 Controller can be required在其他组件中(同样适用于指令)。

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

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

因为这发生在指令链接期间,所以所需的 Controller 在 Controller 构造函数中不可用,这就是为什么 $onInit magic method在那儿。如果存在,it is executed right after adding required controllers这个

两者

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 是一个简洁的样式。

关于javascript - 在 Angular 分量中使用 'require',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35293680/

相关文章:

javascript - Angular Ui.router $state 模板 ng-models 是 $rootScope

angular - 自定义指令在 Angular 模块内不起作用?

javascript - Angular 隔离范围和属性

javascript - iPad 上的按钮点击问题和模糊

javascript - 不使用服务器端语言(也许是javascript?)来获取状态代码

javascript - ngOptions 中的重复项

angular - 如何使用异步管道值处理 `ngIf`?

javascript - 在其他选择中禁用选项

javascript - d3.js中 ".getComputedTextLength()"的等价方法

angularjs - 设置 ng-htmljs-preprocessor karma 预处理器