Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a $scope variable from parent controller to be defined

I have an AngularJS controller which loads data from a service (doing asynchronous $http requests).

And in a child controller, I need to wait for this data to be loaded before I can do another $http request to load some more detailed information.

I tried doing this in the child controller :

$scope.$parent.watch('dataLoaded', function(dataLoaded) {
  if (dataLoaded) {
    // call the service doing the subsequent $http request with data from parent controller
  }
};

When I do this, it works in the child controller, but it seems like the 'dataLoaded' variable (which goes from false to true once data is loaded in parent controller) never have its value actually changed to true in the parent controller.

What am I doing wrong ? Should I use a completely different approach?

like image 820
Hexalyse Avatar asked Oct 27 '15 12:10

Hexalyse


1 Answers

The point here is - we need a reference to be watched (a dot in the name). E.g. Model: {}

So, in parent state/view we would declare it

$scope.Model = {
   dataLoaded: false,
};

And child view can $watch that model property changes (but not on parent, just on current scope)

$scope.$watch('Model.dataLoaded', function(dataLoaded) {
  if (dataLoaded) {
      ...
  }
});

See more details here:

How do I share $scope data between states in angularjs ui-router?

like image 50
Radim Köhler Avatar answered Sep 25 '22 14:09

Radim Köhler