Diolor
Diolor

Reputation: 13450

Angularjs wait until

I have:

$scope.bounds = {}

And later in my code:

$scope.$on('leafletDirectiveMap.load', function(){
    console.log('runs');
    Dajaxice.async.hello($scope.populate, {
                'west' : $scope.bounds.southWest.lng,
                'east': $scope.bounds.northEast.lng,
                'north' : $scope.bounds.northEast.lat,
                'south': $scope.bounds.southWest.lat,
    });
});

The bounds as you can see at the begging they are empty but they are loaded later (some milliseconds) with a javascript library (leaflet angular). However the $scope.$on(...) runs before the bounds have been set so the 'west' : $scope.bounds.southWest.lng, returns an error with an undefined variable.

What I want to do is to wait the bounds (southWest and northEast) to have been set and then run the Dajaxice.async.hello(...).

So I need something like "wait until bounds are set".

Upvotes: 5

Views: 16627

Answers (2)

Pieter Herroelen
Pieter Herroelen

Reputation: 6066

If you want to do this every time the bounds change, you should just use a $watch expression:

$scope.$watch('bounds',function(newBounds) {
   ...          
});

If you only want to do it the first time the bounds are set, you should stop watching after you've done your thing:

var stopWatching = $scope.$watch('bounds',function(newBounds) {
  if(newBounds.southWest) {
     ...
     stopWatching();
  }
});

You can see it in action here: http://plnkr.co/edit/nTKx1uwsAEalc7Zgss2r?p=preview

Upvotes: 4

Ivan Chernykh
Ivan Chernykh

Reputation: 42186

You can use $watch for this purpose, something like this:

 $scope.$on('leafletDirectiveMap.load', function(){

       $scope.$watch( "bounds" , function(n,o){  

           if(n==o) return;

           Dajaxice.async.hello($scope.populate, {
               'west' : $scope.bounds.southWest.lng,
               'east': $scope.bounds.northEast.lng,
               'north' : $scope.bounds.northEast.lat,
               'south': $scope.bounds.southWest.lat,                
            });

       },true);
 });

Upvotes: 5

Related Questions