【问题标题】:jQuery datepicker not working inside ng-repeat in angularjs?jQuery datepicker 不能在 angularjs 中的 ng-repeat 中工作?
【发布时间】:2015-08-04 08:57:40
【问题描述】:

我在 angularjs 中使用 jquery ui 日期选择器,它工作正常。但是当 datepicker 进入 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
            });
        }
    }
})

我该如何解决这个问题?

【问题讨论】:

  • 你能展示你的ng-repeat循环吗? - 已添加,谢谢
  • 它在文本框中
  • 究竟是什么不起作用?您是否看到带有日期值的输入?

标签: javascript jquery angularjs datepicker


【解决方案1】:

问题是您的 DOM 将有多个 &lt;input&gt;s 和 .date_picker 类,因此您的 jQuery 选择器 $(".date_picker") 将随着 ng-repeat 的增长返回越来越多的匹配项。您真的只是希望您的 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 中没有看到&lt;otForm>。

【讨论】:

  • 这里的元素不是文本框。整个模板
  • 也许您可以将指令更改为 restrict: 'A' 并将 otForm 作为属性添加到您的 &lt;input&gt;: &lt;input otForm type="text" ... &gt; 以便您的指令仅映射到相关元素。
  • 我为 datepicker 创建了一个指令,现在它正在工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2017-12-22
  • 2014-07-24
  • 2013-06-19
相关资源
最近更新 更多