javascript Angular.js <input type="date"> 更改提交值的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23105959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular.js <input type="date"> change format of submitted value
提问by user3531335
<label>From</label>
<input type="date" ng-model="startDate"/>
<label>To</label>
<input type="date" ng-model="endDate"/>
<button class="btn btn-success" ng-click="getStatistics(startDate, endDate)">Update</button>
**JS***
**JS***
$scope.getStatistics = function(startDate, endDate) {
$http.get('/admin/api/stats?start=' + startDate + '&end=' + endDate).success(function(data) {
$scope.stats = data;
});
}
The code above push startDate and endDate value on url, but the problem i have is that the submitted value is like 2014-12-01 and i want my format to be 01-05-2014
上面的代码在 url 上推送 startDate 和 endDate 值,但我遇到的问题是提交的值类似于 2014-12-01,我希望我的格式为 01-05-2014
Any suggestions?
有什么建议?
回答by moribvndvs
Unfortunately, browsers that implement a specific element type for handling dates (such as Chrome) use the OS date format, and none that I'm aware of let you change the format (it's not even in the W3C spec). Furthermore, if the browser does not support it (most of them), it uses a regular text input but only accepts data in ISO-8601 format, which makes matters worse.
不幸的是,实现用于处理日期的特定元素类型的浏览器(例如 Chrome)使用操作系统日期格式,而我所知道的没有一个允许您更改格式(它甚至不在 W3C 规范中)。此外,如果浏览器不支持它(大多数),它使用常规文本输入但只接受 ISO-8601 格式的数据,这让事情变得更糟。
Personally, I avoid type="date"
because as is, it's pretty much worthless, unless you're on a mobile device that supports it (such as iOS). So if you can, use a text input, and if you want it to convert the text value into a date object to assign to your model, as well as reformat it upon being updated, you'll need to find or write a directive to do this. There is the UI-Bootstrap date picker, but it does not reformat the date for you and brings along more stuff than perhaps you need. There may be others, too.
就个人而言,我避免这样做,type="date"
因为它几乎毫无价值,除非您使用的是支持它的移动设备(例如 iOS)。因此,如果可以,请使用文本输入,并且如果您希望它将文本值转换为日期对象以分配给您的模型,以及在更新时重新格式化它,您需要找到或编写一个指令做这个。有UI-Bootstrap 日期选择器,但它不会为您重新格式化日期并带来比您需要的更多的东西。可能还有其他人。
However, in the spirit of answering your question, I put together a demo directive that both reformats the entered date to the format of your choice (using Angular's $date
filter). It'll reformat on paste, blur/change, or after a brief pause of inactivity after typing a date in (the latter may not work particularly well in the real world, but it looks kinda cool. take it out if it's weird). The other shortfall is it uses the browser's default mechanism for parsing a Date
. If this is insufficient, replace it with something that is. I'm sure it's far from production-ready, but it's a start. If it's useful enough, I'll turn it into a formal module on Github.
但是,本着回答您的问题的精神,我整理了一个演示指令,将输入的日期重新格式化为您选择的格式(使用 Angular 的$date
filter)。它会在粘贴、模糊/更改或在输入日期后短暂暂停后重新格式化(后者在现实世界中可能效果不佳,但看起来有点酷。如果它很奇怪,请将其取出)。另一个不足是它使用浏览器的默认机制来解析Date
. 如果这还不够,请用它代替。我确信它还远未准备好生产,但这是一个开始。如果够用,我会把它转成 Github 上的正式模块。
angular.module("demo.directives", [])
.directive('date', ['$filter', '$timeout', function($filter, $timeout) {
return {
restrict: 'A',
require: '?^ngModel',
link: function($scope, $element, $attrs, ngModel) {
var format = $attrs.dateFormat || 'short', // default date format
validityName = 'date'; // change the name to whatever you want to use to check errors
// called by the directive to render the first time, and also on events when the value is changed
var formatter = function() {
var date = ngModel.$modelValue ?
$filter('date')(ngModel.$modelValue, format) :
ngModel.$viewValue;
$element.val(date);
};
// parse the value when it is being set from the view to the model
ngModel.$parsers.unshift(function(value) {
// you may wish to use a more advanced date parsing module for better results
var date = new Date(value);
if (isNaN(date)) {
// invalid date, flag invalid and return undefined so we don't set the model value
ngModel.$setValidity(validityName, false);
return undefined;
}
// clear invalid flag
ngModel.$setValidity(validityName, true);
return date;
});
// used by ngModel to display to render the directive initially; we'll just reformat
ngModel.$render = formatter;
var handle;
// trigger the formatter on paste
$element.on('paste cut', function() {
if (handle) $timeout.cancel(handle);
handle = $timeout(formatter, 0); // needs to break out of the current context to work
})
// you can axe this whole event if you don't like the reformat after a pause
$element.on('keydown', function() {
if (handle) $timeout.cancel(handle);
handle = $timeout(formatter, 750);
})
// trigger the formatter on blur
$element.on('blur change', formatter);
}
};
}]);
Usage:
用法:
Include the directive from this plunkin module, then in your HTML use
在模块中包含此 plunk中的指令,然后在您的 HTML 中使用
<input type="text" date date-format="short" ng-model="myDateValue" />
回答by Alexandre Nucera
Well, the input date gives you a date to the ISO format. If you wish to format the date, you would probably need a function like this one :
好吧,输入日期为您提供了ISO 格式的日期。如果你想格式化日期,你可能需要一个这样的函数:
function formatDate(isoDateString)
{
var newDate = new Date(isoDateString);
return ('0' + newDate.getDate()).slice(-2)+"-"+('0' + (newDate.getMonth() + 1)).slice(-2)+"-"+newDate.getFullYear();
}
I add +1 to the month because getMonth returns you a number between 0 and 11. The slice(-2) is for the leading 0.
我给月份加了 +1,因为 getMonth 会返回一个 0 到 11 之间的数字。 slice(-2) 用于前导 0。
回答by Prashobh
Use Filter concept
使用过滤器概念
angular.module('yourmodule').filter('date', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd-MM-yyyy');
return _date.toUpperCase();
};
});
<span>{{ d.time | date }}</span>
or in controller
或在控制器中
var filterdatetime = $filter('date')( $scope.date );