LoginSignup
2
3

More than 5 years have passed since last update.

AngularJS のディレクティブのコントローラでインジェクトするサービスを動的に決めるには

Posted at

AngularJS のディレクティブコントローラでインジェクトするサービスをディレクティブの属性で指定して決めるのに、link で 該当タグの HTML 属性からインジェクトしたいサービスの文字列を取得し、 $injector.get を呼び出すコントローラのメソッドを実行しました。以下のコードは Angular v1.4.1, ES6 です。

<my-hoge filter="AaaFilter"></my-hoge>
class HogeDirectiveController {
  constructor($injector) {
    this.$injector = $injector;
  }
  setFilter(filter) {
    this.filter = this.$injector.get(filter);
  }
}

HogeDirectiveController.$inject = ['$injector'];


function HogeDirective($parse) {
  return {
    restrict: 'E',
    controller: HogeDirectiveController,
    controllerAs: 'dctrl',
    scope: {},
    link: function (scope, element, attrs, controller) {
      scope.dctrl.setFilter(attrs.filter);
    },
    template: `
  <input ng-model="dctrl.filter.piyopiyo">
`
  };
}

angular.module('MyAdmin').directive('myHoge', HogeDirective)
export default HogeDirective;
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3