srjjio
srjjio

Reputation: 1049

Wait for external script dynamically loaded in AngularJS 1

Because I get my external API key from internal API, I would like to dynamically load external script in my app.js file.

import common from './common';

angular.module('app', [common])
  .run(['$rootScope', 'configService', ($rootScope, configService) => {
    $rootScope.googleApiIsReady = false;
    configService.getConfig().then((res) => {
      let script = document.createElement('script');
      script.setAttribute('type', 'text/javascript');
      script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + res.data.GOOGLE_MAP_API_KEY + '&libraries=places&language=en-US');
      document.getElementsByTagName('head')[0].appendChild(script);
      $rootScope.googleApiIsReady = true;
    }); 
  }]) 
;

The sample of code above works fine (external library loaded in sources) but I don't know how to handle it in controller or directive to wait it is correctly loaded before execute some instructions.

I have a form page with autocomplete input using this API. If I directly refresh this page, the app doesn't have the time to load this external librairy before the autocomplete directive failed to be instanciated. I need to find a way to wait the library to be loaded or to reinstanciate the directive after it is loaded or find a cleaner way to load the lib.

module.directive("autoComplete", function($rootScope) {
  return {
    restrict: 'A',
    link : function(scope, elm, $attrs) {
       $rootScope.$watch('googleApiIsReady', function() {
         if ($rootScope.googleApiIsReady) {
           ...
         }
       }, true);  
    }
  };
});

Upvotes: 1

Views: 1856

Answers (1)

srjjio
srjjio

Reputation: 1049

As suggested by @lakshay, a workaround is to apply a timeout before changing the root scope value.

setTimeout(() => {
  // Wait 1 sec before active auto completion for the google map libs to be loaded.
  $rootScope.googleApiIsReady = true;
}, 1000);

Upvotes: 2

Related Questions