我在表单中有两个日期选择器。当用户选择第一个日期时,应更新第二个日期选择器的最小和最大日期(距离选择一年)。但在我的情况下,当我第一次在第一个datepicker中选择日期时,最小和最大日期只更新一次。但是,如果我更改选择,则第二个日期选择器不会使用更改的值进行修改。
HTML:
<div class="form-group">
<label>Model Production Date</label>
<input date-picker1 type="text" class="form-control" placeholder="Production Date" ng-model="productionDate">
</div>
<div class="form-group">
<label>Next Review Date</label>
<input date-picker2 type="text" class="form-control" placeholder="Next Review Date" ng-model="nextReviewDate">
</div>
JS:
.directive('datePicker1', function () {
return function (scope, element, attrs) {
element.datepicker({
format: "yyyy/mm/dd",
todayHighlight: true,
//startDate: stDate || new Date(),
//endDate:enDate || new Date(),
autoclose: true
});
scope.$watch('productionDate', function (newVal, oldVal) {
if(newVal){
scope['productionDate'] = newVal;
}
else{
return;
}
});
};
})
.directive('datePicker2', function () {
return {
restrict: 'A',
link: linker,
}
function linker(scope, $element, attrs) {
scope.$watch('productionDate', function (newVal, oldVal) {
console.log('productionDate===='+scope.productionDate);
splittedDateString = scope.productionDate.split('/');
stDate = new Date(splittedDateString[0], splittedDateString[1]-1, splittedDateString[2]);
enDate = new Date(stDate.getFullYear()+1, splittedDateString[1]-1, splittedDateString[2]);
console.log("Start Date = "+stDate);
console.log("End Date = "+enDate);
$element.datepicker({
format: "yyyy/mm/dd",
todayHighlight: true,
startDate: stDate || new Date(),
endDate:enDate || new Date(),
autoclose: true
});
});
};
})
每次我都可以看到stDate
和enDate
值已更改,但第二个datepicker开始日期和结束日期未更新。我被困了2天。请帮忙
答案 0 :(得分:0)
将值传递给指令时,会创建隔离范围。您可以使用指令的scope属性定义如何处理传递给此指令的值。
.directive('datePicker2', function () {
return {
scope: {
name: "=",
},
link: linker
}
function linker (scope, element, attrs) {
scope.$watch('productionDate', function (newVal, oldVal) {
console.log('productionDate===='+scope.productionDate);
splittedDateString = scope.productionDate.split('/');
stDate = new Date(splittedDateString[0], splittedDateString[1]-1, splittedDateString[2]);
enDate = new Date(stDate.getFullYear()+1, splittedDateString[1]-1, splittedDateString[2]);
element.datepicker({
format: "yyyy/mm/dd",
todayHighlight: true,
startDate: stDate || new Date(),
endDate:enDate || new Date(),
autoclose: true
});
if(newVal){
scope['nextReviewDate'] = newVal;
}
else{
scope['nextReviewDate'] = setDate();
}
});
};
}