【问题标题】:AngularJS - Jquery datatable emptyAngularJS - Jquery 数据表为空
【发布时间】:2014-05-25 22:33:02
【问题描述】:

我正在尝试使用 angular 和 jquery 数据表显示数据表,但到目前为止,在应用数据表函数后数据表仍为空。

我读到最好的方法是使用指令,但我无法让它工作。只有我设法让它工作是通过应用 100 毫秒的超时(超时小于 100 不起作用)

我想做的是在渲染 DOM 后应用数据表函数。我敢肯定有人已经做到了;)

userController.js

myApp.controller('UserController', ['$scope', 'User',
    function ($scope, User) {

        User.query(function(data) {
            $scope.users = data;
        }, function(errorData) {
        });

    }]);

datatableSetup.js

myApp.directive('datatableSetup', ['$timeout',
    function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, elm, attrs) {
                $timeout(function() {
                    elm.dataTable();
                }, 100);
            }
        }
    }]);

user.html

<table datatable-setup="" class="table table-bordered table-striped">
<thead>
<tr>
    <th>Username</th>
    <th>Roles</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
    <td>{{user.username}}</td>
    <td>
        <ul>
            <li ng-repeat="role in user.roles">
                {{role}}
            </li>
        </ul>
    </td>
</tr>
</table>

【问题讨论】:

    标签: javascript jquery angularjs jquery-datatables


    【解决方案1】:

    在将 DataTables 插件与 AngularJS 集成并使用 DOM 作为数据源时,您需要等待 DOM 完成渲染,然后再调用“dataTable()”。

    如果您正在检索要异步呈现的数据,您还需要等待该数据可用。

    我的猜测是,在这种情况下,您使用的 100 毫秒延迟足以让这两个都完成。

    要在 DOM 渲染后运行某些东西,您通常可以将调用包装在 $timeout 中,而无需指定延迟。这会将调用放在执行队列的末尾,当它运行时,Angular 应该已经完成​​了 $digest 循环,并且应该已经渲染了所有内容:

    app.directive('datatableSetup', ['$timeout',
      function($timeout) {
        return {
          restrict: 'A',
          link: function(scope, element, attrs) {
    
            $timeout(function () {
              element.dataTable();
            });
          }
        }
      }
    ]);
    

    现在您需要确保:

    1. 在异步调用的数据可用之前,不会编译指令
    2. 在异步调用的数据可用之前,指令链接中的 $timeout 代码不会运行

    如果您想走第一条路线,您可以在表格元素上放置ng-if,以延迟 DOM 部分的创建(以及指令的编译),直到数据可用。您可以检查 users 数组是否包含数据,或者在数据加载完成时将变量设置为 true:

    <table ng-if="users.length" datatable-setup class="table table-bordered table-striped">
    

    演示: http://plnkr.co/edit/Zx2E3cuqPFXe2nhqySXv?p=preview

    对于第二条路线,有多种选择。例如,您可以在使用时取消注册的链接函数中使用观察者,使用 $broadcast/$emit 甚至是服务或一些自定义通知系统。

    【讨论】:

    • 正是我需要的!谢谢你的解释。
    • ng-if 的使用对我有用。我认为这很酷而且很直接。
    猜你喜欢
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多