I have a form where I need users to enter time, in the resource this is saved as minutes (or milliseconds, a simple change). I need a directive to get the second / millisecond value, then create 3 separate inputs for minutes, seconds and milliseconds.
Users can then modify each of the components, and the directive will then update the model with second / millisecond values ββof the three components.
It seems I can take the model value, create 3 inputs and use moment.js to create the individual components of time.
Directive
angular.module('myExampleApp') .directive('lapTimeInput', function () { var tpl = '<div class="lap_time_input"> \ <input ng-model="lap_time.minutes" type="number" class="minutes" placeholder="00" min="0" max="15" step="1"> \ <span class="lap-time-sep">:</span> \ <input ng-model="lap_time.seconds" type="number" class="seconds" placeholder="00" min="0" max="59" step="1"> \ <span class="lap-time-sep">.</span> \ <input ng-model="lap_time.milliseconds" type="number" class="milliseconds" placeholder="000" min="0" max="999" step="1"> \ </div>'; return { restrict: 'A', template: tpl, replace: true, require: 'ngModel', scope: { }, link: function (scope, element, attrs, ngModel) { if (!ngModel) return; scope.$watch(function () { return ngModel.$modelValue; }, function(newValue) { // Using moment.js to extract min, sec & ms parts var duration = moment.duration(newValue, 'seconds'); scope.lap_time = { minutes: duration.minutes(), seconds: duration.seconds(), milliseconds: duration.milliseconds() } }); } }; });
controller
$scope.lap = Lap.get({ id: 1 }); // $resource contains .lap_time property // OR $scope.lap = { lap_time: 90.999 }
HTML
<input type="text" lap-time-input ng-model="lap.lap_time" />
This plunker hopefully will be a little clearer
http://plnkr.co/edit/xmNtlItembSUFFZzaT9n?p=preview
Now I'm not even sure that I went the right way with $ watch on ngModel, I would not have guessed. As far as I understand, I need a directive to do 3 things:
- Replace the element with three separate inputs for minutes, seconds, and milliseconds.
- Show model value to user in created inputs using created inputs
- When the user changes any of the three inputs, he updates the model value by turning 3 separate values ββfor seconds / milliseconds.
Even just pushing in the right direction would be a big help