我有一个angularjs应用程序,可跟踪家庭成员数据。 DOB是更重要的领域之一。我使用以下溢出帖子来创建自定义datepicker指令 jQuery ui datepicker with Angularjs
这是代码
//jquery datepicker through angular
angularApp.directive('datepicker', function() {
return {
restrict: 'A',
require : 'ngModel',
link : function (scope, element, attrs, ngModelCtrl) {
$(function(){
element.datepicker({
dateFormat:'mm/dd/yy',
minDate: new Date(1910,0,1),
yearRange:'1910:+0',
changeMonth: true,
changeYear: true,
onSelect:function (date) {
// ngModelCtrl.$setViewValue(date);
scope.date = date;
scope.$apply();
}
});
});
}
};
});
现在,我的问题有所不同,然后发现的其他帖子是,我只能通过单击“添加新成员”按钮创建的新家庭成员得到
Missing instance data for this datepicker
。以下是示例错误 http://plnkr.co/edit/DdFMbNIEp39cg3yE1ar6?p=preview的链接。要复制该问题,请尝试家庭成员1(第一组字段)的DOB。 DOB选择器应正常工作,现在选择“单击以添加其他家庭成员”。这将为家庭成员2添加新字段,如果您单击DOB字段,日历将弹出,但您将无法选择日期-同样,测试字段也不会填充。
最佳答案
通过在指令中添加console.log(),我可以确定angularjs html编译器无法编译动态ID。console.log("xxxxxx-1 " + $(element)[0].id);
无论我创建了多少家庭成员,他们都具有相同的ID:xxxxxx-1 HOUSEHOLD{{ $index + 1 }}_dob
通过将transclude标志设置为true并添加时间延迟,我们可以允许编译器在尝试选择日期之前完成其工作。
//jquery datepicker through angular
angularApp.directive('datepicker', function($timeout) {
var linker = function (scope, element, attrs, ngModelCtrl) {
$timeout( function(){
$(element).datepicker({
dateFormat:'mm/dd/yy',
minDate: new Date(1910,0,1),
yearRange:'1910:+0',
changeMonth: true,
changeYear: true,
onSelect: function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
};
return {
restrict: 'A',
require : 'ngModel',
transclude: true,
link : linker,
};
});