5

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

1
  • Not sure if this is just a typo or not, but your $scope.bound = {}; is missing an 's' so $scope.bounds. doesn't exist and therefore is undefined. Alternatively, you should use $scope.$watch('bounds',function(newVal,oldVal){ .. stuff here ..}) to see if the variable has changed and loaded what you want. Commented Oct 17, 2013 at 13:33

2 Answers 2

5

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);
 });
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.