のらねこの気まま暮らし

技術系だけど、Qiita向きではないポエムとかを書くめったに更新されないヤツ

AngularJSでdirectiveを作ってみる

2014-03-25っていう文字列の日付をyear, month, dayの3つのフォームに分割して入力したい、と思った。

一つのngModelからフォーマットを変えてinputを並べればいいとおもって、directiveを使ってみた記録。

<input type="date" name="year"     ng-model="user.birth_on">
<input type="date" name="month" ng-model="user.birth_on">
<input type="date" name="day"     ng-model="user.birth_on">

directiveの作り方

ngModelController$formattersというプロパティがArrayで存在するので、そいつにフォーマット用のfunctionを登録してやる。

  • $filterを利用してdateを整形する
  • 整形文字列は、ui-date-formatの属性で指定できるようにする
    • 例)ui-date-format="yyyy"
  • フォーマットする文字列はmodelから取ってくる
angular.module("app")
  .directive("uiDateFormat", [
    "$filter",
    function ($filter) {
      return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {
          ctrl.$formatters.push(function (view_value) {
            return $filter("date")(view_value, attrs.uiDateFormat);
          });
        }
    }
  ]);
<input type="date" name="year"     ng-model="user.birth_on" ui-date-format="yyyy">
<input type="date" name="month" ng-model="user.birth_on" ui-date-format="M">
<input type="date" name="day"     ng-model="user.birth_on" ui-date-format="d">

ui-dateというAngular UIのライブラリ

ui-dateを使えばいいという気はしつつ、ui-dateはjquery-uiとjqueryに依存しているし、そこまでの機能は必要なさそうだった。 なので、勉強を兼ねて作ってみた。