繁体   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 ***

$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)使用OS日期格式,而我所知没有一个可以更改格式(甚至在W3C规范中也没有)。 此外,如果浏览器不支持(大多数)浏览器,则使用常规文本输入,但仅接受ISO-8601格式的数据,这会使情况变得更糟。

就我个人而言,我避免使用type="date"因为按原样,它几乎毫无价值,除非您使用的是支持它的移动设备(例如iOS)。 因此,如果可以,请使用文本输入,并希望将文本值转换为日期对象以分配给模型,并在更新后对其进行重新格式化,则需要查找或编写指令以做这个。 UI-Bootstrap日期选择器 ,但它不会为您重新格式化日期,并且带来的东西可能超出您的需要。 可能还有其他。

但是,本着回答您的问题的精神,我编写了一个demo指令,该指令将输入的日期重新格式化为您选择的格式(使用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之间的数字。slice(-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 );

日期过滤和格式化

暂无
暂无

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

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