Search code examples
angularjsangular-promiseangular-controller

Accessing parent controller $scope data after load in angular


I have the following situation in angular:

  1. I load json data from a database on init() to a variable "data" and would like to use the variable "data" in a child controller (nested).
  2. Because the loading from the database takes some time, the variable $scope.data in the child controller outputs as "undefined".

What is an elegant way to handle this situation? Do I need to use a promise on parent's init method inside the child controller? I would appreciate an example :).

// Parent Controller
app.controller('pCTRL', function($scope) {
  $scope.init = function(id){} 
  //sets my variable $scope.data successfully via a rest API
  //and for test, sets $scope.x to "blabla"
}

//Child Controller
app.controller('cCTRL', function($scope) {
console.log($scope.x); //outputs blabla properly
console.log($scope.data); // undefined

Thank you for your feedback!


Solution

  • A common solution is to use a watcher. For example:

    app.controller('cCTRL', function($scope) {
        $scope.$watch('data', function(newVal){
            console.log(newVal); // outputs actual value
        });
    }
    

    This is only needed if you need to have logic in the directive. If you just want to display data in the cCTRL template you don't need the above watcher, angular will update the template when the parent changes.