jQuery angularjs 中的 ng-repeat 中的日期选择器不工作?

jQuery datepicker not working inside ng-repeat in angularjs?

我在 angularjs 中使用 jquery ui 日期选择器并且工作正常。但是当日期选择器进入 ng-repeat 循环时它不起作用。

<input type="text" class="form-control date_picker" ng-model="date.date" ng-repeat="date in ot.dates">
//Directive
app.directive('otForm', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'app/components/ots/form.html',
        link: function ($scope, form) {
            $(".date_picker").datepicker({
                dateFormat: 'dd-mm-yy',
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
                showButtonPanel: false,
                changeYear: true,
                changeMonth: true
            });
        }
    }
})

我该如何解决这个问题?

问题是您的 DOM 将有多个 <input>.date_picker 的 class,因此您的 jQuery 选择器 $(".date_picker") 将随着 ng-repeat 的增长而 return 越来越多的匹配项。你真的只是想让你的 jQuery 选择器匹配你的 ng-repeat 中的一个指令元素。你很幸运,因为指令中的 link 函数将 scopeelement 本身传递给你:

<input type="text" class="form-control date_picker" ng-model="date.date" ng-repeat="date in ot.dates">
//Directive
app.directive('otForm', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'app/components/ots/form.html',
        link: function (scope, element, attrs) {
            $(element).datepicker({
                dateFormat: 'dd-mm-yy',
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
                showButtonPanel: false,
                changeYear: true,
                changeMonth: true
            });
        }
    }
})

查看 link: 行和紧跟其后的行的更改。我假设您的指令已正确实施,但未在此处显示。你有 restrict: 'E',但我在你的 ng-repeat 中没有看到 <otForm>。