2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

2
Posted at

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

.html
<my-hoge filter="AaaFilter"></my-hoge>
.javascript
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?