Using 'require' in angular component

后端 未结 1 1318
萌比男神i
萌比男神i 2020-12-11 01:27

According to the docs (specifically, the table comparing directives to components), angular components allow requiring other directives (or is it only components?). However,

相关标签:
1条回答
  • 2020-12-11 01:57

    The cited source is outdated. As of 1.5.0, component controllers can be required in other components (the same applies to directives).

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

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题