Angularjs wait until

16,415

Solution 1

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);
 });

Solution 2

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

Share:
16,415
Diolor
Author by

Diolor

Autodidact programmer by passion. Among others I work with: Kotlin, RxJava, Android Currently working at car2go.

Updated on June 16, 2022

Comments

  • Diolor
    Diolor about 2 years

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

  • Diolor
    Diolor over 10 years
    No clue how, but i works. I know what the basic $watch does but what does the if(n==o) return; and the true do at the end?
  • Ivan Chernykh
    Ivan Chernykh over 10 years
    @Diolor function(n,o) gets old and new value of bounds , and if they are equal it does nothing and simply returns. true means: Compare object for equality rather than for reference.