Child Controller loading before Parent controller api call in angularjs

575 views Asked by At

I am using angular 1.6, I have one parent state and child state with their respective controllers. In my first login page, there will be two links calling parent state & child state. When I am called parent state, it was working fine. But calling child state from login page, there will be some error in console like 'id' undefined. I am making one Restangular api request in parent controller. After this response I need to load child controller? But when I am calling child state directly, child controller loads before parent controller api calls to finish. How to resolve this?

look at this plunker.

https://embed.plnkr.co/aUnHIzuFV7GpiDuKyrwZ/

1

There are 1 answers

0
georgeawg On

In the parent controller save the promise from the API call:

$scope.restPromise = Restangular.one('collections')
.get()
.then(function(data){ 
  $state.go("parentstate.childstate");
  $scope.myData = data;
  $scope.params={
  name:"my_name",
  type:"generic",
  data:data
  };     
});

In the child controller, use the promise to wait for the API call:

function ChildCtrl($scope) {
  $scope.restPromise.then(function() {
    console.log($scope.params);
    $scope.params.id=5;
    $scope.title = 'Child State';
  });
}

The DEMO on PLNKR