Angular-UI日期选择器的初始状态未按照日期选择器弹出窗口格式化。

18

我正在使用一个 angular-ui 日期选择器,一切都很正常,除了日期选择器的初始状态。在选择了一个日期后,它看起来很好。如下所示:

初始状态

输入图像描述

选择日期后

输入图像描述

显然,在第一种情况下,我得到的是日期对象的字符串化版本,在选择日期后则为格式化版本。

标记

<input type="text" class="form-control"
       id="birthday"
       datepicker-options="datePickerOptions"
       datepicker-popup="{{format}}"
       data-ng-model="birthday"
       data-is-open="opened"
       data-ng-required="true"
       data-close-text="Close"/>

<span class="input-group-btn">
    <button type="button"
            class="btn btn-default"
            data-ng-click="open($event)">
        <i class="fa fa-calendar"></i>
    </button>
</span>

控制器

var today = $scope.today = function today() {
    $scope.birthday = $scope.client.birthday || new Date();
};
today();

$scope.clear = function clear() {
    $scope.dt = null;
};

$scope.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
};

$scope.format = 'MMM d, yyyy';
$scope.datePickerOptions = {
    'show-weeks': false
};

虽然不是很重要,但如果模型(根据文档需要是日期对象)最初就按照$scope.format格式化而不是作为字符串化的日期对象格式化,那将会非常好。 另外,不确定是否有影响,但此日期选择器位于模态框内。 感谢您的任何帮助!

更新

看起来我不是唯一遇到这个问题的人,这与使用 Angular 1.3 相关。 https://github.com/angular-ui/bootstrap/issues/2659

4个回答

4

我发现的解决方案都很繁琐,需要使用指令等,所以我更喜欢这种简短的方法。

birthday = $filter('date')(new Date(), "MMM dd, yyyy");

注意: 不要忘记将Angular内置的$filter服务注入到控制器中。

angular.module('app').controller("yourController", 
['$filter' function($filter){ 
       /* your code here */  

       birthday = $filter('date')(new Date(), "MMM dd, yyyy");

       /* your code here */ 
}]);

希望这能帮到您。

不幸的是,这会将绑定属性转换为字符串而不是日期,然后一旦选择了另一个日期,它将被转换回日期,因此像Andreas Ågren的解决方案一样,您必须在提交之前进行一些类型检查。 - csharpsql
为了改进这个,将一个监视器添加到你正在使用的日期字段中,将会添加一个单独的答案。 - csharpsql

3

我遇到了类似的问题,看起来 Bootstrap UI 与 AngularJS 1.3.x 版本不兼容。

这个 plunkr 对我有所帮助,http://plnkr.co/edit/L9u12BeeBgPC2z0nlrLZ?p=preview

// this is the important bit:
.directive('datepickerPopup', function (){
  return {
    restrict: 'EAC',
    require: 'ngModel',
    link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
    }
  }
});

也请参考Github工单https://github.com/angular-ui/bootstrap/issues/2659#issuecomment-60750976


对我来说完美地工作了!谢谢,这是angularjs库的问题..我的版本是1.3,只需将其注入到您的指令中,您就应该没问题了! - Manam

1
为了改进Premchandra Singh的回答,使用angular $filter服务确实有效,但是您还需要在日期字段上添加一个watch以在将来更新时应用过滤器:
$scope.myDate = $filter('date')(new Date(), 'dd.MM.yy');
$scope.$watch('myDate', function (newValue, oldValue) {
    $scope.myDate = $filter('date')(newValue, 'dd.MM.yy');
});

0

除了在github问题中描述的方法之外,对我而言另一个有效的解决办法是使用以毫秒为单位的纪元时间来初始化模型,而不是使用日期对象,例如:

$scope.dt = new Date().getTime();

1
这种方法可以解决显示问题,但它会将你绑定的模型变量转换成时间戳整数而不是日期对象。如果在弹出窗口中单击日期时不会将其转换回日期对象,那么这并不是太糟糕,这意味着使用它的代码需要先进行繁琐的类型检查。 - Fasermaler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接