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);  
    }
  };
});
8
  • the external api is being loaded in .run(). It should load as soon as the app is loaded therefore i don't think if there is any need for applying wait. are u facing any problem? Commented Oct 27, 2017 at 9:41
  • I have completed the question. Commented Oct 27, 2017 at 9:48
  • why not add the script in your index.html file Commented Oct 27, 2017 at 9:53
  • I could not since I need API key (which I got from a service) in script element url. Commented Oct 27, 2017 at 10:15
  • 1
    then apply timeout on your directive Commented Oct 27, 2017 at 12:03

1 Answer 1

2

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

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.