Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 576
Diolor Avatar asked Oct 17 '13 11:10

Diolor


2 Answers

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);
 });
like image 61
Ivan Chernykh Avatar answered Nov 19 '22 23:11

Ivan Chernykh


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

like image 41
Pieter Herroelen Avatar answered Nov 20 '22 00:11

Pieter Herroelen