简体   繁体   English

Angular.js <input type=“date”> 更改提交值的格式

[英]Angular.js <input type=“date”> change format of submitted value

<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? 有什么建议么?

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). 不幸的是,实现特定元素类型以处理日期的浏览器(例如Chrome)使用OS日期格式,而我所知没有一个可以更改格式(甚至在W3C规范中也没有)。 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. 此外,如果浏览器不支持(大多数)浏览器,则使用常规文本输入,但仅接受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). 就我个人而言,我避免使用type="date"因为按原样,它几乎毫无价值,除非您使用的是支持它的移动设备(例如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. UI-Bootstrap日期选择器 ,但它不会为您重新格式化日期,并且带来的东西可能超出您的需要。 There may be others, too. 可能还有其他。

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 ). 但是,本着回答您的问题的精神,我编写了一个demo指令,该指令将输入的日期重新格式化为您选择的格式(使用Angular的$date过滤器 )。 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 . 另一个不足之处是它使用浏览器的默认机制来解析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. 如果足够有用,我将其转换为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 plunk in module, then in your HTML use 在模块中包含插件的指令 ,然后在HTML中使用

 <input type="text" date date-format="short" ng-model="myDateValue" />

Well, the input date gives you a date to the ISO format . 好吧,输入日期会为您提供ISO格式的日期。 If you wish to format the date, you would probably need a function like this one : 如果您希望格式化日期,则可能需要这样的功能:

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。

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 );

Date filtering and formatting 日期过滤和格式化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM