【发布时间】:2016-12-21 13:53:17
【问题描述】:
我有两个自定义日期选择器指令。一个称为 startDatePicker 指令,第二个称为 endDatePicker。我正在将模型从一个传递到另一个,这很好,但是当我将日期作为字符串传递时,它不会显示日期。我知道它不应该因为 datepicker 需要日期对象并且它不能自动将其转换为日期对象。因为我的后端服务器将日期作为字符串返回,所以我需要转换为日期对象。为此,我在指令中使用 model.$formatter 将字符串转换为日期对象,然后将其发送到视图,以便可以选择和显示日期。日期已被选中,但未显示.. 为了模拟这个问题,我在控制器中定义了两个变量。这两个也将用于日期选择器模型。第一个变量被选中并显示在日期选择器中,但第二个变量只被选中,但不显示。我做错了什么?
$scope.startDate = moment.utc("2016/12/25 00:00:00")._d;
$scope.endDate = "2016/12/25 00:00:00";
我已经设置 plunker 来显示问题 http://plnkr.co/edit/trEkwuO06VMJ1HdCkl5w?p=preview
下面的完整指令
angular.module('ui.bootstrap.demo').directive('endDatepicker', function() {
return {
restrict: 'A',
scope: {
ngModel: "=",
minStartDate: "=",
},
require: 'ngModel',
replace: true,
templateUrl: 'datepicker-template.html',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function getJsonDate(date) {
if (!date) return null;
console.log("Unformatted date " + date)
var newDate = moment.utc(date)._d;
console.log("Formatter fired " + newDate)
return newDate
});
scope.popupOpen = false;
scope.openPopup = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.popupOpen = true;
};
console.log(scope.endDate);
scope.$watch('minStartDate', function(newValue,oldValue){
if (newValue) {
console.log(newValue)
scope.dateOptions.minDate = newValue;
}
})
scope.dateOptions = {
startingDay: 1,
minDate: moment.utc()._d
}
scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
scope.opened = true;
};
}
};
});
【问题讨论】:
标签: angularjs datepicker