LoginSignup
3
4

More than 5 years have passed since last update.

TypeScript用ng-modelを使うdirectiveのテンプレ

Last updated at Posted at 2016-01-06

対応バージョン

  • Angular 1.4.8
  • TypeScript 1.7.5

で動作確認。

バリデーション系directive

module foo {
    angular.module('bar').directive('hoge', () => {
        return {
            restrict: 'A',
            scope: {},
            require: ['ngModel'],
            priority: -1,
            controller: HogeCtrl
        };
    });

    class HogeCtrl {
        /* @ngInject */
        constructor($element: ng.IAugmentedJQuery) {
            var ngModel: ng.INgModelController = $element.controller('ngModel');
            ngModel.$validators['hoge'] = (modelValue, viewValue) => {
                var v = modelValue || viewValue;
                return true;
            };
        }
    }
}

独自input系directive

module foo {
    angular.module('bar').directive('hoge', () => {
        return {
            restrict: 'E',
            scope: {},
            require: ['ngModel'],
            priority: -1,
            controller: HogeCtrl,
            controllerAs: 'ctrl',
            replace: true,
            template: `<div>hoge</div>`
        };
    });

    interface IHogeData {}

    class HogeCtrl {
        ngModel: ng.INgModelController;
        /* @ngInject */
        constructor($element: ng.IAugmentedJQuery) {
            this.ngModel = $element.controller('ngModel');
        }

        get data(): IHogeData {
            return this.ngModel.$viewValue;
        }

        set data(hogeData: IHogeData) {
            this.ngModel.$setViewValue(hogeData);
        }
    }
}

補足

  • /* @ngInject */olov/ng-annotateで自動的にinjectの例のヤツを付けるためのもの。
  • priority: -1は過去のngModelのpriorityが0だったことがあったので一応。基本は付けなくても問題ないかも。
  • scaffold用のテンプレを作ると捗ります。

補足2

@shuhei さん曰く、/* @ngInject */より、今は"ngInject";と書いたほうが良いそうです。

class A {
    constructor($scope: ng.IScope) {
        "ngInject";
    }
}
3
4
3

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
4