问题
<input type="text" ng-model="user.User.DateOfBirth">
is in my view. user.User.DateOfBirth
is currently in YYYYMMDD
format, but I want it to show as mm/dd/yyyy
format in the view. Is it possible to convert this just for the display?
回答1:
For outputting the data in the correct format try filters (in your case the date filter: http://docs.angularjs.org/api/ng.filter:date)
Well, for inputs that's another case. I guess you could always bind that input to another property, watch that and parse it yourself and then assign it to your real model...
Some more insight, you could try something like this:
HTML:
<input type="text" ng-model="myDateInput">
In your JS controller use the following:
$scope.$watch('myDateInput', function (newValue) {
$scope.user.User.DateOfBirth = $filter('date')(newValue, 'yyyy-MM-dd'); // Or whatever format your real model should use
});
$scope.$watch('user.User.DateOfBirth', function (newValue) {
$scope.myDateInput = $filter('date')(newValue, 'yyyy-MM-dd'); // Or whatever format your input should use
});
It would probably be better though to force the user to use a certain input format, either by some sort of pattern matching (and therefore validation) or by some sort of special date input/widget.
回答2:
This also may help you
http://jsfiddle.net/mikeeconroy/Hu9m2/1/
.filter('myFormatDateFilter',function(){
return function(input){
if(angular.isDefined(input)){
if(input.length >= 8){
input = input.slice(0,8);
input = input.slice(4,6) + '/' + input.slice(6,8) + '/' + input.slice(0,4);
}
}
return input;
};
});
来源:https://stackoverflow.com/questions/20004255/how-do-i-format-data-in-a-view-in-angularjs