Forked from kolen/angular_momentjs_binding_directive.js
Last active
August 29, 2015 14:26
-
-
Save brainwire/6574c965bbd1a68ff2e9 to your computer and use it in GitHub Desktop.
Two-way binding between form field and moment.js date object for angular.js. With validation.Date object is in UTC, form field displays local date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
directive('dateBinding', function() { | |
//var format = "YYYY-MM-DD HH:mm:ss" | |
//date.isValid() is not enough for strict validation, see moment.js doc | |
//var pattern = /^\s*\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}(:\d{2})?\s*$/ | |
var parseFormat = attrs.dateBinding; | |
return { | |
restrict: 'A', | |
require: 'ngModel', | |
link: function(scope, element, attr, ngModel) { | |
ngModel.$parsers.push(function(text) { | |
var date = moment(text, parseFormat) | |
ngModel.$setValidity('dateInvalid', date.isValid()) //&& text.match(pattern)) | |
return date | |
}) | |
ngModel.$formatters.push(function(datetime_moment) { | |
return datetime_moment && datetime_moment.local().format(parseFormat) | |
}) | |
} | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment