How to format date using ng model?
I have an input defined as
<input class="datepicker" type="text" ng-model="clientForm.birthDate" /> which is configured to display elsewhere on the page:
<tr> <th>Birth Date</th> <td>{{client.birthDate|date:'mediumDate'}}</td> </tr> When the page loads, the date of birth is nicely formatted as something like Dec 22, 2009 . However, when I look at my <input> , it displays as Tue Dec 22 2009 00:00:00 GMT-0800 (Pacific Standard Time) , which I suppose is that JS displays Date objects as strings.
First, how to tell Angular to show the date in <input> as something like 12/22/2009 ? I cannot apply |filters to the ng-model attribute.
Secondly, as soon as I edit the date, even saving it in its original format, my other text (inside the <td> ) doesn't seem to apply the |date filter anymore; it unexpectedly changes formats to match the format of the input text field. How to make it apply the |date filter every time the model changes?
Related questions:
- How do I get my directive to enable onchange only?
- How to access arguments in a directive?
Use custom form validation http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
Directive using formatters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) { return { require:'^ngModel', restrict:'A', link:function (scope, elm, attrs, ctrl) { var moment = $window.moment; var dateFormat = attrs.moDateInput; attrs.$observe('moDateInput', function (newValue) { if (dateFormat == newValue || !ctrl.$modelValue) return; dateFormat = newValue; ctrl.$modelValue = new Date(ctrl.$setViewValue); }); ctrl.$formatters.unshift(function (modelValue) { if (!dateFormat || !modelValue) return ""; var retVal = moment(modelValue).format(dateFormat); return retVal; }); ctrl.$parsers.unshift(function (viewValue) { var date = moment(viewValue, dateFormat); return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : ""; }); } }; }); Here is a very convenient angular-datetime directive. You can use it as follows:
<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="myDate"> It also adds a mask to your entry and performs validation.
I created a simple directive that allows the standard elements of the input[type="date"] form to work correctly with AngularJS ~ 1.2.16.
Take a look here: https://github.com/betsol/angular-input-date
And here is the demo: http://jsfiddle.net/F2LcY/1/
Since you used datepicker as a class, I assume you are using jQuery datepicker or something similar.
There is a way to do what you intend without using moment.js at all, using only the datepicker and angularjs directives.
I gave an example here in Fiddle
Excerpts from the violin here:
Datepicker has a different format, and the format of angularjs is different, you need to find the appropriate match so that the date is pre-selected in the control and also filled in the input field when the ng model is attached. The following format is equivalent to the
'mediumDate'format of the AngularJS format.$(element).find(".datepicker") .datepicker({ dateFormat: 'M d, yy' });The date input directive must have an intermediate string variable to represent a readable date form.
Updating through different sections of the page should occur through events such as
$broadcastand$on.Using a filter to represent a date in a human-readable form is also possible in the ng-model, but with a temporary variable of the model.
$scope.dateValString = $filter('date')($scope.dateVal, 'mediumDate');
I am using jquery datepicker to select a date. My directive date and converting it to json date format (in milliseconds) is stored in ng-model data during date.and reverse date display, if ng-model has json date (in milliseconds) my formatting display is in my format as jquery datepicker .
HTML code:
<input type="text" jqdatepicker ng-model="course.launchDate" required readonly /> Angular Directive:
myModule.directive('jqdatepicker', function ($filter) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModelCtrl) { element.datepicker({ dateFormat: 'dd/mm/yy', onSelect: function (date) { var ar=date.split("/"); date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]); ngModelCtrl.$setViewValue(date.getTime()); scope.$apply(); } }); ngModelCtrl.$formatters.unshift(function(v) { return $filter('date')(v,'dd/MM/yyyy'); }); } }; }); I use the following directive, which makes me and most users very happy! It uses the moment for parsing and formatting. This is a bit like the one mentioned earlier by SunnyShah.
angular.module('app.directives') .directive('appDatetime', function ($window) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { var moment = $window.moment; ngModel.$formatters.push(formatter); ngModel.$parsers.push(parser); element.on('change', function (e) { var element = e.target; element.value = formatter(ngModel.$modelValue); }); function parser(value) { var m = moment(value); var valid = m.isValid(); ngModel.$setValidity('datetime', valid); if (valid) return m.valueOf(); else return value; } function formatter(value) { var m = moment(value); var valid = m.isValid(); if (valid) return m.format("LLLL"); else return value; } } //link }; }); //appDatetime In my form, I use it as follows:
<label>begin: <input type="text" ng-model="doc.begin" app-datetime required /></label> <label>end: <input type="text" ng-model="doc.end" app-datetime required /></label> This will bind the timestamp (milliseconds since 1970) to doc.begin and doc.end .
I prefer the server to return the date unchanged, and javascript does an array scan. My API returns "MM / DD / YYYY hh: mm: ss" from SQL Server.
Resource
angular.module('myApp').factory('myResource', function($resource) { return $resource('api/myRestEndpoint/', null, { 'GET': { method: 'GET' }, 'QUERY': { method: 'GET', isArray: true }, 'POST': { method: 'POST' }, 'PUT': { method: 'PUT' }, 'DELETE': { method: 'DELETE' } }); } ); controller
var getHttpJson = function () { return myResource.GET().$promise.then( function (response) { if (response.myDateExample) { response.myDateExample = $filter('date')(new Date(response.myDateExample), 'M/d/yyyy'); }; $scope.myModel= response; }, function (response) { console.log(response.data); } ); }; MyDate Validation Directive
angular.module('myApp').directive('myDate', function($window) { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { var moment = $window.moment; var acceptableFormats = ['M/D/YYYY', 'MD-YYYY']; function isDate(value) { var m = moment(value, acceptableFormats, true); var isValid = m.isValid(); //console.log(value); //console.log(isValid); return isValid; }; ngModel.$parsers.push(function(value) { if (!value || value.length === 0) { return value; }; if (isDate(value)) { ngModel.$setValidity('myDate', true); } else { ngModel.$setValidity('myDate', false); } return value; }); } } } ); HTML
<div class="form-group"> <label for="myDateExample">My Date Example</label> <input id="myDateExample" name="myDateExample" class="form-control" required="" my-date maxlength="50" ng-model="myModel.myDateExample" type="text" /> <div ng-messages="myForm.myDateExample.$error" ng-if="myForm.$submitted || myForm.myDateExample.$touched" class="errors"> <div ng-messages-include="template/validation/messages.html"></div> </div> </div> template / checks / messages.html
<div ng-message="required">Required Field</div> <div ng-message="number">Must be a number</div> <div ng-message="email">Must be a valid email address</div> <div ng-message="minlength">The data entered is too short</div> <div ng-message="maxlength">The data entered is too long</div> <div ng-message="myDate">Must be a valid date</div> Angularjs ui bootstrap you can use angularjs ui bootstrap, it also provides date checking
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min-date="minDate" max-date="'2015-06-22'" datepickeroptions="dateOptions" date-disabled="disabled(date, mode)" ng-required="true">
the controller can specify any format that you want to display as a date-filter.
$ scope.formats = ['dd-MMMM-yyyy', 'yyyy / MM / dd', 'dd.MM.yyyy', 'shortDate'];