我昨天开始使用AngularJS 1.3,我发现的一个问题是Datepicker中的初始日期不是定义的格式。 选择日期后,日期格式正确。
AngularJS 1.2.10的初始格式是正确的,可以通过注释掉脚本标记在示例中看到。
如何将初始格式设置为正确?
HTML
<!doctype html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<!-- <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script> -->
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<br>
<br>
<div ng-controller="DatepickerDemoCtrl">
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min-date="minDate" max-date="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
</div>
</body>
</html>
JS
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller("DatepickerDemoCtrl", function ($scope) {
$scope.format = 'dd-MMMM-yyyy';
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
});
答案 0 :(得分:34)
不确定1.3中究竟发生了什么变化,但有一个bug report for this。
这是一个初始值的drop-in指令,用于修复问题,直到修复bug为止。这是一个演示Plunker。
angular.module('myApp').directive('datepickerPopup', function (dateFilter, datepickerPopupConfig) {
return {
restrict: 'A',
priority: 1,
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var dateFormat = attr.datepickerPopup || datepickerPopupConfig.datepickerPopup;
ngModel.$formatters.push(function (value) {
return dateFilter(value, dateFormat);
});
}
};
});
答案 1 :(得分:6)
app.controller("DatepickerDemoCtrl", function ($scope,$filter) { .. // $filter added
$scope.today = function() {
$scope.dt = $filter('date')(new Date(), $scope.format);
};
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" ... // {{format}} added
请检查这三项修改。