我想将 Angular UI 日期选择器限制在作为变量传入的两个日期之间。我最好在不添加像 momentjs 这样的库的情况下让它工作,因为这是我需要处理日期的唯一领域。
这里是这个问题的一个plunker:
http://plnkr.co/edit/zsjpoVZtHqJLIP2RW6vm?p=preview
这里是变量:
mycurrentdate = '2016-04-18'
mymindate = '2016-04-01'
mymaxmonth = '2016-05-01'
mymaxdate will be calculated from mymaxmonth to be
mymaxdate = '2016-05-31'
我的实际最大日期将是 mymaxmonth 的最后一天
$scope.maxDate = new Date(
$scope.mymaxmonth + (TO THE END OF THE MONTH)
);
需要注意的一件事是,通过 new Date()
运行它会返回给定日期前一天的日期。例如:
$scope.minDate = new Date(
$scope.mymindate
);
$scope.minDate 返回 Wed Mar 30 2016 17:00:00 GMT-0700 (PDT)
我查找了它返回 3 月 30 日而不是 4 月 1 日的原因,它看起来像是时区错误?
我想将 mymindate 设置为 '2016-04-01' 并获取 mymaxdate = '2016-05-31' 并禁用此范围之外的所有日期。我读过 Beginners Guide to Javascript Date and Time并在这里试用。
在我的 Controller 中:
$scope.mymindate = '2016-04-01';
$scope.mymaxmonth = '2016-05-01'; //want mymaxdate to be '2016-05-31'
$scope.minDate = new Date($scope.dt.getFullYear(), $scope.dt.getMonth(), 1);
$scope.maxDate = new Date($scope.dt.getFullYear(), $scope.dt.getMonth() + 1, 0);
在我的模板中:
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
最佳答案
您需要为您的输入
设置带有适当选项
的datepicker-options
来禁用日期。在您的示例中使用了 datepicker-options="dateOptions"
但在您的 Controller 中没有声明 dateOptions
。
因此您需要为maxDate
和minDate
设置dateOptions
。喜欢
$scope.dateOptions = {
maxDate: new Date($scope.maxDate),
minDate: new Date($scope.mymindate)
};
并设置 maxDate
和 minDate
如下:
$scope.mymindate = new Date('2016-04-01');
$scope.mymaxmonth = new Date('2016-05-01'); //wanted mymaxdate to be '2016-05-31'
$scope.minDate = new Date($scope.mymindate);
$scope.maxDate = new Date($scope.mymaxmonth.getFullYear(),$scope.mymaxmonth.getMonth()+1,0);
和 HTML:
<p class="input-group">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" min="minDate" max="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
可以看到Plunker Demo希望它能帮到你 :)
关于javascript - AngularUI Datepicker 禁用超出范围的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699224/