angularjs datepicker指令动态表单字段上的“缺少实例数据”

时间:2015-06-03 16:37:40

标签: jquery angularjs jquery-ui datepicker

我有一个跟踪家庭成员数据的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(第1组字段)的DOB。 DOB选择器应该工作,现在选择“单击以添加其他家庭成员”。这将为家庭成员2添加新字段,如果您单击DOB字段,日历将弹出,但您将无法选择日期 - 此外,测试字段将不会填充。

1 个答案:

答案 0 :(得分:3)

通过在指令中添加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,
};

});

相关问题