Skip to content

Instantly share code, notes, and snippets.

@weihanchen
Last active August 9, 2016 12:42
Show Gist options
  • Save weihanchen/800c088528de1e3bea27a48d51d2e9c2 to your computer and use it in GitHub Desktop.
Save weihanchen/800c088528de1e3bea27a48d51d2e9c2 to your computer and use it in GitHub Desktop.
angular formatters and parsers
'use strict';
(function() {
angular.module('notes')
.directive('displayDate', [displayDate])
function displayDate() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
//format text from the user (view to model)
ngModelCtrl.$parsers.push(function(data) {
return moment(new Date(data)).format();
});
//format text going to user (model to view)
ngModelCtrl.$formatters.push(function(data) {
return moment(new Date(data)).format(attrs.format);
})
}
}
}
})();
<div class="table-responsive">
<table >
<tbody class="no-borders">
<tr>
<td>
<h3 class="control-label">Date Time Picker: </h3>
</td>
<td>
<input class="form-control"
format=""
ng-model="formatterParserCtrl.dateTime"
display-date />
</td>
</tr>
<tr>
<td>
<h3 class="inline">Model Value: </h3>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
'use strict';
(function() {
angular.module('notes')
.controller('formatterParserController', [formatterParserController])
function formatterParserController() {
var self = this;
self.dateFormat = 'YYYY-MM-DD';
self.dateTime = new Date();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment