AngularJSでjQuery datetimepickerを使うためのディレクティブの作成

前提

要素 バージョン
AngularJS 1.4.1
jQuery 3.1.1
jQuery datetimepicker 2.5.4

概要

初めてAngularJSのディレクティブを自作したので舞い上がって投稿する。

本記事では。属性ディレクティブ”dateTimePicker”を定義し、以下のように利用できるようにする

呼び出し

<date-time-picker ng-model="datetime" format="Y/m/d" time=false />

パラメータ

パラメータ名 入力例 説明
ng-model datetime バインディングするAngularJSのデータモデル
format Y/m/d 入力される日時文字列のフォーマット
time true 時刻の入力を行うか

実行例

ディレクティブの作成

パラメータで指定しない部分については、以下の固定値を与えている
– bootstrap用のclassを設定する(form-control)
– AngularJS用のバリデーションを設定(required)
– 各種スクロールをオフにする

angular.module('app').directive('dateTimePicker', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    scope: {
      format: "@",
      time: "@",
    },
    replace: true,
    template: '<input type="text" class="form-control date-time-picker" required>',
    link(scope, element, attrs, controller) {
      if (scope.format === undefined) {
        scope.format = 'Y/m/d H:i';
      }
      scope.time = scope.time === 'true' ? true : false;
      $(element).datetimepicker({
        format: scope.format,
        timepickerScrollbar: false,
        timepicker: scope.time,
        scrollMonth: false,
        scrollTime: false,
        scrollInput: false,
        onChangeDateTime(dp, $input) {
          controller.$setViewValue($input.val());
        },
      });
    },
  };
});

ソースコード解説

行番号 抜粋 説明
01 directive(‘dateTimePicker’… ディレクティブ dateTimePickerを作成する
03 restrict: ‘E’ <dateTimePicker>の形式で利用できるようにする
04 require: ‘ngModel’ ng-model属性の指定を必須にする
05-08 scope: { 属性(format/time)を文字列で受け取る
09 replace: true, タグをtemplateで置き換える
10 template: ‘<input type=”text”… タグを置き換えるテンプレート
11-27 link(scope, element, attrs, controller) { ディレクティブの挙動を定義
16-26 $(element).datetimepicker({ datetimepickerの呼び出し
24 controller.$setViewValue($input.val()); datetimepickerによって値が書き換わった時に手動でデータバインディングする

実行結果

実行前

<date-time-picker format="Y/m/d H:i" time=true ng-model="blog.post.datetime"/>

実行後

<input type="text" class="form-control date-time-picker ng-isolate-scope ng-valid ng-valid-required ng-touched" required="" format="Y/m/d" time="false" ng-model="weight.post.date">

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です