【问题标题】:Using 'require' in angular component在角度组件中使用“要求”
【发布时间】:2016-05-19 12:49:36
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs angular-directive


    【解决方案1】:

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

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

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

    因为这发生在指令链接期间,所需的控制器在控制器构造函数中不可用,这就是$onInit magic method 存在的原因。如果存在,it is executed right after adding required controllersthis

    两者

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-22
      • 2020-08-25
      • 2018-01-13
      • 2016-04-27
      • 2019-03-19
      • 2014-11-18
      • 2017-05-24
      • 2017-04-12
      相关资源
      最近更新 更多