AngularJS延迟视图显示

时间:2017-03-12 04:00:57

标签: javascript html angularjs

我的控制器从两个外部JSON文件中获取数据,过滤它然后应该在视图上呈现。但是整个操作需要一些时间(约30毫秒)并且视图首先被加载。因此,HTML代码无法找到数据。

如何延迟加载视图以便首先从控制器加载数据?或者可能有另一种解决方案?

$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

}

2 个答案:

答案 0 :(得分: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服务

答案 1 :(得分:0)

关于assignRatePlans()

的成功,请致电$http

试试这个

$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

}