Angular.js<输入类型=";日期">更改提交值的格式

Angular.js <input type="date"> change format of submitted value

本文关键字:quot 提交 格式 gt 日期 输入 js 类型 Angular lt      更新时间:2023-09-26
<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***

$scope.getStatistics = function(startDate, endDate) {
    $http.get('/admin/api/stats?start=' + startDate + '&end=' + endDate).success(function(data) {
        $scope.stats = data;
    });
}

上面的代码在url上推送startDate和endDate值,但我的问题是提交的值像2014-12-01,我希望我的格式是01-05-2014

有什么建议吗?

不幸的是,实现用于处理日期的特定元素类型的浏览器(如Chrome(使用操作系统日期格式,据我所知,没有一个允许您更改格式(W3C规范中甚至没有(。此外,如果浏览器不支持它(大多数(,它会使用常规文本输入,但只接受ISO-8601格式的数据,这会使情况变得更糟。

就我个人而言,我避免使用type="date",因为它实际上毫无价值,除非你使用支持它的移动设备(如iOS(。因此,如果可以的话,使用文本输入,如果你希望它将文本值转换为日期对象以分配给你的模型,并在更新时重新格式化它,你需要找到或编写一个指令来做到这一点。有一个UI Bootstrap日期选择器,但它不会为你重新格式化日期,并带来比你可能需要的更多的东西。可能还有其他人。

然而,本着回答您问题的精神,我编写了一个演示指令,将输入的日期重新格式化为您选择的格式(使用Angular的$date过滤器(。它会在粘贴、模糊/更改时重新格式化,或者在输入日期后短暂暂停不活动后重新格式化(后者在现实世界中可能不太好用,但看起来有点酷。如果很奇怪,就把它拿出来(。另一个不足是它使用浏览器的默认机制来解析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);
      }
    };
  }]);

用法:

包括这个插件模块的指令,然后在HTML中使用

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

输入日期会为您提供ISO格式的日期。如果你想格式化日期,你可能需要这样一个功能:

function formatDate(isoDateString)
{
  var newDate = new Date(isoDateString);
  return ('0' + newDate.getDate()).slice(-2)+"-"+('0' + (newDate.getMonth() + 1)).slice(-2)+"-"+newDate.getFullYear();
}

我在月上加+1,因为getMonth会返回一个0到11之间的数字。切片(-2(用于前导0。

使用过滤器概念

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>

或在控制器中

var filterdatetime = $filter('date')( $scope.date );

日期过滤和格式化