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に依存しているし、そこまでの機能は必要なさそうだった。 なので、勉強を兼ねて作ってみた。