[英]Angular JS Data loading Before Page Loading
我想在AngularJS Page Load之前加載數據。 我在Angualr上也使用bootstrap和JQuery。 主要問題是我在頁面上有表格,並使用JQuery進行分頁和其他過濾器,包括響應性。
現在發生了什么,該頁面加載了所有JQuery,后來我的數據出現在頁面上,沒有什么像分頁等。我做了以下解決方法:
<script>
$(function () {
// document.body.style.overflow = 'hidden';
setTimeout(
function()
$('#example1').DataTable({
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"scrollX": true
});
}, 500);
});
</script>
我添加了手動延遲等待JQuery,以便該頁面之前加載其數據。
任何人都可以告訴好的解決方案,如何確保在頁面HTML呈現之前加載數據?
我強烈建議不要使用jQuery進行分頁。 還有其他解決方案可以讓Angular魔法為你工作,比如ui-grid,smart-table等。這些都需要你很少的努力。
如果你真的想繼續沿着這條道路前進,那么你可以通過$routeProvider.when
的決心獲得你想要的東西。 當請求路由時,解析塊將首先運行任何promise,並在轉到該路由之前等待它們解析。 Resolve還可以將該數據傳遞到路徑的控制器中:
.when('/route', {
...,
resolve: {
dataYouWant: function(DataGettingService) {
return DataGettingService.get();
}
}
})
這只是一種可能的解決方案。 您也可以使用指令而不是控制器
angular
.module('app', [])
.factory('repository', function ($http) {
var loadData = function () {
return $http... ;//make http call here and return the promise
};
return {
loadData: loadData
};
})
.controller('myCtrl', function (repository) {
repository.loadData().then(function(data) {
// use loaded data here
$('#example1').DataTable({
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"scrollX": true
});
});
});
您需要以某種方式將您的jQuery代碼與Angular綁定。 這是指令嘗試。
app.directive('jqueryCallDirective' , function() {
return {
link: function(scope, element, attrs) {
element.DataTable({
"paging": true,
...
});
}
}
});
然后對元素使用ng-if延遲渲染:
<div id="example1" ng-if="hasData" jquery-call-directive> ... </div>
然后在適當的范圍$scope.hasData = true
適當的時間設置$scope.hasData = true
(如果可以接受的話,只在$ rootScope上設置)。 希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.