is there a simple way to apply a filter to a input? i've found some examples, but all sounds like a Macgyver solution for me. My form is defined dynamically, and when the input type is date
, i need to convert date value from 2000-01-01T02:00:00.000Z
to mm/dd/yyyy
.
<form role="form">
<div ng-repeat="fld in grid.columns">
<label>{{fld.label}}</label>
<input type="text" ng-model="grid.currentRecord[fld.name]">
</div>
</form>
I could not use that suggestion in my case: ( filters on ng-model in an input )
anybody help me, plese?
the simplest way that i found:
i've created a directive called 'dateformatter', that basically, define a $formatter
to filter value viewed in input, and a $parser
to treat value before set it into model:
app.directive('dateformatter', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
return new Date(viewValue)
});
ctrl.$formatters.push(function(modelValue) {
return modelValue.toDateString()
});
}
};
});
and i added 'dateformatter' attribute in input tag:
<form role="form">
<div ng-repeat="fld in grid.columns">
<label>{{fld.label}}</label>
<input type="text" dateformatter ng-model="grid.currentRecord[fld.name]">
</div>
</form>
it's working out!
Expanding upon your own answer, you could use moment.js , wrap it into an AngularJS service, and create a really flexible solution:
.directive('dateFormat', ['moment', function (moment) {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, $element, $attrs, ngModelCtrl) {
ngModelCtrl.$parsers.unshift(function (viewValue) {
return moment(viewValue, $attrs.dateFormat).toDate();
});
ngModelCtrl.$formatters.push(function (modelValue) {
return moment(modelValue).format($attrs.dateFormat);
});
}
};
}])
which would be used like this:
<input type="text" ng-model="some.model" date-format="MM/DD/YYYY">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.