[英]AngularJS - Jquery datatable empty
我正在嘗試使用angular和jquery數據表顯示數據表,但到目前為止,數據表在應用數據表函數后仍保持空白。
我已經讀過,最好的方法是使用指令,但我不能讓它工作。 這只是我設法讓它工作是通過應用100毫秒的超時(超過100的時間不起作用)
我想要做的是在呈現DOM之后應用datatable函數。 我確定有人設法做到了;)
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>
在將DataTables插件與AngularJS集成並使用DOM作為數據源時,您需要等待DOM在調用' dataTable()
'之前完成渲染。
如果要檢索要異步呈現的數據,則還需要等待該數據可用。
我的猜測是,在這種情況下,你使用的100ms延遲足以讓這兩個延遲完成。
要在DOM渲染之后運行某些東西,通常可以將調用包裝在$timeout
而不指定延遲。 這將把調用放在執行隊列的末尾,當它運行時,Angular應該已經完成$ digest循環並且所有內容都應該被渲染:
app.directive('datatableSetup', ['$timeout',
function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$timeout(function () {
element.dataTable();
});
}
}
}
]);
現在你需要確保:
如果你想要第一個路徑,你可以在表元素上放置一個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甚至是服務或某些自定義通知系統。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.