0

My controller fetch data from two external JSON files, filter it and then should render on the view. But whole operation take some time (approximately 30 mil sec) and view is loaded first. So data cannot be found by HTML code.

How can I delay loading of my view in order to load data from controller first? Or maybe there is another solution?

$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
  • use something like $scope.dataHasLoaded = false to initialize hiding your view and then when the async operation has finished set to true in conjunction with ng-if Commented Mar 12, 2017 at 4:41
  • In your case I think that the better approach is use the resolve object of the routing to load the async data, so when the controller is instantiated, your data will be available. Tell me if your are using ui router or simple ngRoute and I can show you and example. Commented Mar 12, 2017 at 4:44

2 Answers 2

1

Can use $q.all() which doesn't resolve until all of the input promises are resolved

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
  });

Note: Remember to inject $q service

Sign up to request clarification or add additional context in comments.

Comments

0

Call assignRatePlans() on the success of the $http

Try this

$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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.