2017-03-12 165 views
0

我的控制器從兩個外部JSON文件中獲取數據,對其進行過濾,然後在視圖上進行渲染。但是整個操作需要一些時間(大約30毫秒)並且首先加載視圖。所以數據不能被HTML代碼找到。AngularJS延遲視圖顯示

如何延遲加載我的視圖以便首先從控制器加載數據?或者也許有另一種解決方案?如果您使用多個HTTP請求上的$http

成功

$scope.ratePlansRelated = []; 

$http.get('rooms.json').then(function(res){ 
    $scope.rooms = res.data; 
}); 

$http.get('ratePlans.json').then(function(res){ 
    $scope.ratePlans = res.data; 
}); 

// delay calling that function in order to load data from json first 
setTimeout(assignRatePlans,25); 


function assignRatePlans() 
{ 
    //filter data and assing it to $scope.ratePlansRelated here 

} 
+0

使用像'$ scope.dataHasLoaded = FALSE '初始化隱藏你的視圖,然後當異步操作完成與'ng-if'一起設置爲'true'時 –

+0

在你的情況下,我認爲更好的方法是使用路由的解析對象來加載異步數據,所以當控制器實例化後,您的數據將可用。告訴我,如果你正在使用ui路由器或簡單的ngRoute,我可以告訴你和例子。 –

回答

0

呼叫assignRatePlans()試試這個

$scope.ratePlansRelated = []; 
var ratePlansDone = false; 
var roomsDone = false; 


$http.get('ratePlans.json').then(function(res){ 
    $scope.ratePlans = res.data; 
    ratePlansDone = true; 
    if (roomsDone) { 
     assignRatePlans(); 
    } 
}); 


$http.get('rooms.json').then(function(res){ 
    $scope.rooms = res.data; 
    roomsDone = true; 
    if (ratePlansDone) { 
     assignRatePlans(); 
    } 
}); 



function assignRatePlans() 
{ 
    //filter data and assing it to $scope.ratePlansRelated here 

} 
+0

這是不是一個好主意,寫HTTP http req –

+0

@sachilaranawaka編輯我的答案現在檢查:) –

+0

現在很好,但它更好,如果你可以連鎖請求 –

0

那麼你可以連這些請求,並調用承諾內assignRatePlans功能。

function getRoom() { 
    return $http.get('rooms.json'); 
} 
function ratePlans(){ 
    return $http.get('ratePlans.json'); 
} 
getRoom().then(function(res) { 
    $scope.rooms = res.data; 
    return ratePlans() 
}) 
.then(function(res) { 
    $scope.ratePlans = res.data; 
    assignRatePlans() 
}); 

function assignRatePlans() 
{ 
    //filter data and assing it to $scope.ratePlansRelated here 

} 
1

可以使用$q.all()不解決,直到所有的輸入承諾的決心

var req1 = $http.get('ratePlans.json').then(function(res){ 
    $scope.ratePlans = res.data;  
});  

var req2 = $http.get('rooms.json').then(function(res){ 
    $scope.rooms = res.data;  
}); 

$q.all([req1, req2]) 
    .then(assignRatePlans) 
    .catch(function(err){ 
     // do something if either request fails 
    }); 

注意:請記住注入$q服務