在AngularJs未按预期工作的情况下更改输入日期的格式

Changing the format of an input date with AngularJs not working as expected

本文关键字:情况下 输入 格式 日期 工作 AngularJs      更新时间:2023-09-26

好吧,我想显示一个输入日期字段,但格式已更改。

我的意思是,默认格式是:yyyy-MM-dd (2015-11-20),但我想要它:(11-20-2015)

我用momentjs找到了一个jsfiddle(没有角度),它的工作方式完全符合我的要求。

使用AngularJs时,我也使用了一个指令,但使用了span字段(并且有效)。但如果我使用输入日期,它就不起作用。

这是html:

<body ng-app="docsTimeDirective">
  <div ng-controller="Controller">
  Current date is: <span my-current-time="format"></span><hr/>
  <input type="date" ng-model="myDate.value" my-current-time="format">
</div>
</body>

Js:

(function(angular) {
  'use strict';
angular.module('docsTimeDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.format = 'MM/dd/yyyy';
    $scope.myDate = {
      value: new Date()
    };
  }])
  .directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {
    function link(scope, element, attrs) {
      var format,
          timeoutId;
      function updateTime() {
        element.text(dateFilter(new Date(), format));
        console.log(dateFilter(new Date(), format));
      }
      scope.$watch(attrs.myCurrentTime, function(value) {
        format = value;
        updateTime();
      });
      element.on('$destroy', function() {
        $interval.cancel(timeoutId);
      });
      // start the UI update process; save the timeoutId for canceling
      timeoutId = $interval(function() {
        updateTime(); // update DOM
      }, 1000);
    }
    return {
      link: link
    };
  }]);
})(window.angular);

这是Plunker。一些想法?

这是因为.text()不会应用于<input />元素。您将需要.val()

你可以做一个非常基本的检查来涵盖这两种情况。请遵守以下(未经测试)。。。

element[0].value !== undefined ? element.val(/*...*/) : element.text(/*...*/)

此外,根据讨论,请记住完全缺乏对type="date"的跨浏览器支持。也许在这里找到一个现成的日期选择器可能最符合你的利益,也可能解决你的格式限制问题。

好吧,我用两种方法解决了我的问题:

1)利用动量Js

attrs.$set('myCurrentDate', momentFilter(date, format));

然后

.filter('moment', function () {
    return function (date, formated) {
        moment.locale('es');
        var momented = moment(date).format(formated);
        return momented;
    };
});

查看Plunker


2)使用Javascript本机日期对象

attrs.$set('myCurrentDate', dateFilter(date, format));

查看Plunker


但在这两种情况下,在css的帮助下:

input:before {
    position: absolute;
    top: 3px; left: 3px;
    content: attr(my-current-date);
    display: inline-block;
    color: black;
}

PS:请注意变量$scope.format在这两种情况下的定义之间的差异。


编辑:

但如果我们不想复杂化,我们可以使用AngularUI的优秀日期选择器。它有很多特点。

这让我找到了解决问题的第三种方法:参见Plunker

相关文章: