我正在构建一个向input ['date']元素添加一些逻辑的指令。这就是我现在所拥有的:
app.directive('calendarInput', function() {
'use strict';
return {
template : '<input type="date"' +
'ng-model="calendarInput"' +
'min="{{min}}"' +
'max="{{max}}" />'
replace: true,
scope: {
startdate : '@',
enddate : '@',
calendarInput: '='
},
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch('startdate', function (val) {
if (val) {
var date = new Date(val);
scope.min = date.toIsoString().split('T')[0];
}
});
scope.$watch('enddate', function (val) {
if (val) {
var date = new Date(val);
scope.max = date.toIsoString().split('T')[0];
}
});
}
};
});
想法是重用此指令。有时只有开始日期,有时只有结束日期。像这样:
<div calendar-input="item.birthday" enddate="'1990-01-01'"></div>
不幸的是,这总是导致类的形式无效ng-invalid-min
。这是因为我没有提供startdate参数。
如何使最小值或最大值可选?
编辑:我正在使用Angular 1.3.9
找出了一种按需编译max
和min
属性的方法。
app.directive('calendarInput', function($compile) {
'use strict';
return {
template : '<input type="date" class="datepicker" ng-model="omdCalendarInput" />',
replace: true,
scope: {
startdate : '@',
enddate : '@',
calendarInput: '='
},
restrict: 'CA',
link: function (scope, element, attrs) {
var dateInput = element.find('input') // <----
scope.$watch('startdate', function (val) {
if (val) {
var date = new Date(val);
scope.min = date.toIsoString().split('T')[0];
if (!dateInput.attr('min')) { // <----
dateInput.attr('min', '{{min}}'); // <----
$compile(dateInput)(scope); // <----
}
}
});
scope.$watch('enddate', function (val) {
if (val) {
var date = new Date(val);
scope.max = date.toIsoString().split('T')[0];
if (!dateInput.attr('max')) { // <----
dateInput.attr('max', '{{max}}'); // <----
$compile(dateInput)(scope); // <----
}
}
});
}
};
});
编辑:改进了上面的代码。我也将其标记为正确的答案,因为没有其他人有解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句