2017-03-12 168 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服务