【问题标题】:Error using Datatable with Angularjs将数据表与 Angularjs 一起使用时出错
【发布时间】:2016-12-16 01:12:11
【问题描述】:

我正在尝试使用 Angularjs 框架创建一个 jQuery Datatable,使用此 example 中的第二个答案。一旦 ng-repeat 完成加载表,我将初始化 DataTable()。

会出现箭头、过滤器和搜索栏,但由于某种原因,如果您单击箭头,它们不会排序。它们在上下之间切换,但不排序。当我希望搜索框搜索行中的实际值时,搜索框还会按标题名称搜索。

当单击按钮并收到 HTTP 响应时会填充表格的“itms”,因此在呈现整个表格之前不会调用 .DataTable()。

我还测试了一个表,其中 itms 是硬编码的,它工作得很好。我错过了什么?

JS:

angular.module('abcapp')
.directive('repeatDone', function() {
    return function(scope, element, attrs) {
        if (scope.$last) { // all are rendered
            $('#my-table').DataTable();
        }
    }
})

HTML:

<div ng-if="itms && itms.length > 0" class="row">
 <table id="my-table" class="table table-striped" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <th>d</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <th>d</th>
        </tr>
    </tfoot>
    <tbody>
      <tr ng-repeat="itm in itms track by $index" repeat-done>
        <td>{{itm.a}}</td>
        <td>{{itm.b}}</td>
        <td>{{itm.c}}</td>
        <td>{{itm.d}}</td>
      </tr>
    </tbody>
  </table>
</div>

【问题讨论】:

标签: jquery html angularjs datatables


【解决方案1】:

在 $timeout 中包装 jQuery 调用:

  .directive('repeatDone', function($timeout) {
    return function(scope, element, attrs) {
      if (scope.$last) { // all are rendered
        $timeout(function() {
          $('#my-table').DataTable();
        });
      }
    }
  })

【讨论】:

  • 嗯,不...我查看了他们的文档,时间默认为 0,所以我也尝试将超时设置为 200 毫秒。我试着把 console.log($("#my-table tr"));记录行数,它似乎正确地出来了。
【解决方案2】:

我将 DataTable() 调用放在一个函数包装器中,并且它起作用了。我认为没有调用超时,并且正在调用超时内的函数。我试图在不带括号的情况下指定$(...).DataTable,但出现角度错误,所以这是我的解决方案。

不过遇到了另一个问题...每当表格在第一次填充后更新时,元素都不会改变。

angular.module('...')
.directive('repeatDone', function($timeout) {
    return function(scope, element, attrs) {
        function initWrapper(){
            $('...').DataTable();
        }
        if (scope.$last) {
            $timeout(initWrapper,200);
        }
    }
})

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 2012-12-23
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多