Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - Using 'require' in angular component

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...