I have a directive which has a templateUrl. In the directive, there is a $scope variable initialized as
$scope.mapLoaded = false;
and a method
$scope.onMapLoaded = function(){
$scope.mapLoaded = true;
$scope.$apply();
};
In the $scope.init() function, I am checking that, if the map is loaded, the call a method initAutocomplete() (This method initialize the google address API)
$scope.init = function()
{
console.log('init() is called ' + ' at '+ Date.now());
if($scope.applicationId === undefined || $scope.applicationId == '') return false;
$scope.getAssetLocations($scope.loadAssetLocations);
$scope.getAccountId($scope.loadAccountId);
if($scope.mapLoaded === true){
console.log('[$scope.init] >Map loaded is '+ $scope.mapLoaded + ' at '+ Date.now());
$timeout( function(){
$scope.initAutocomplete();
}, 4000 );
}
};
I am also watching the $scope.mapLoaded variable
$scope.$watch('mapLoaded', function () {
console.log('[$watch(mapLoaded)] >Map loaded is '+ $scope.mapLoaded + ' at '+ Date.now());
if($scope.mapLoaded === true){
$timeout( function(){
$scope.initAutocomplete();
}, 4000 );
}
});
And in the view part, I am checking via jQuery that, if the document is ready, then load the google map.
<html>
..some html here
</html>
<script>
$(document).ready(function () {
console.log('loadGoogleMap is called from ApplicationAsset at '+ Date.now() + ' after the document is ready');
window.setTimeout(loadGoogleMap, 1000);
});
function loadGoogleMap(){
if (window.google && document.getElementById('AppAssetLocation')) {
angular.element(document.getElementById('AppAssetLocation')).scope().onMapLoaded();
console.log('loadGoogleMap called from ApplicationAsset at '+ Date.now());
}
else {
window.setTimeout(loadGoogleMap, 1000);
console.log('Again, loadGoogleMap is trying to call from ApplicationAsset at '+ Date.now());
}
}
</script>
But, what happens here, sometimes it calls window.setTimeout(loadGoogleMap, 1000); inside $(document).ready and sometimes it is not calling. And it is completely random.
What's the problem here folks?
setTimeout? OrloadGoogleMapwithin the timeout? You also have a potential endless loop thereloadGoogleMap, if the firstifis never satisfied it will go toelse, which then restarts the function and will do the same again and again and...