LoginSignup
3
3

More than 5 years have passed since last update.

AngularJS + ES6ならbindToControllerとcontrollerAsを使ってクールにカスタムディレクティブを作ろう

Posted at

従来のポピュラーな作り方

angular.module('SampleApp', [])
  .directive('customDirective', function () {
    return {
      require: ['ngModel'],
      scope: {
        sampleText: '=ngModel'
      },
      template: '<input type="text" ng-model="sampleText">' +
        '<div>nanka</div>',
      link: function (scope, element, attrs) {
        var changeSampleText = function () {
          scope.sampleText = 'changed';
        }

        changeSampleText();
      }
    }
  })
;

ES6でクールな作り方

class CustomDirective {
  require = ['ngModel'];
  scope = {};
  bindToController = {
    sampleText: '=ngModel'
  };
  template = `
    <input type="text" ng-model="ctrl.sampleText">
    <div>nanka</div>
  `;
  controller = CustomDirectiveController;
  controllerAs = 'ctrl';
}

class CustomDirectiveController {
  sampleText;

  constructor () {
    this.changeSampleText();
  }

  changeSampleText () {
    this.sampleText = 'changed';
  }
}

angular.module('SampleApp', [])
  .directive('customDirective', () => new CustomDirective())
;

ごめんなさい

もっとちゃんと説明したいけどわかる人は「あ、素敵」ってなると思ったのでここまで…
時間と余裕があればもう少しマシなコンテンツを用意します。

ありがとうございました!

3
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
3
3