0

i am trying to load google map api link inside ng-src directive using this method..

<script ng-src="{{trustSrc(vCustom.googleMapApi.src)}}"></script>

in my controller i have..

v.googleMapApi = { src: "https://maps.googleapis.com/maps/api/js?key=" + config.googleApiKey + "&libraries=places" };

$scope.trustSrc = function (src) {
        return $sce.trustAsResourceUrl(src);
    }

sometimes it works and some times it doesn't.. The Error

ReferenceError: google is not defined...

i have tried different ways to bind it inside ng-src directive but no success..

it works when i add this script <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> but it doesn't work dynamically.. any help ??

there is no syntax error and my controller is ng-controller="Custom as vCustom"

any suggestions to bind it in ng-src directive ?

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
asad
  • 1
  • 1
  • [bind script element's src attribute](http://stackoverflow.com/questions/27306706/how-to-bind-script-elements-src-attribute-in-angularjs) please read this . I hope you will get your answer – Faris Hameed Jul 26 '16 at 18:19

2 Answers2

0

I think you are trying to lazy load the script. Pls have a look at below post it may help. How to asyncronously load a google map in AngularJS?

Community
  • 1
  • 1
Mahesh
  • 982
  • 8
  • 20
  • no sir that's not the case, the issue is binding inside a ng-src attribute.. and it works like a charm if i hard code google maps script i.e. `` – asad Jul 22 '16 at 07:20
0

Let me try to explain the scenario as best as I can :) The <script> tags are evaluated only once in a web application. Unlike img tags which can have src attribute assigned to different values throughout the app and so are re-evaluated. So what's happening is that sometimes when the compiler gets to your script tag, the model (vCustom.googleMapApi.src) is resolved so it works fine but sometimes it doesn't because the $digest loop (events loop) in angular hasn't finished resolving the model and so the API key isn't passed correctly to script tag which results in not loading the google maps API and then where you're using the map, it throws the error. In that case, to verify, check the script tag on chrome debugger, it won't have the correct API key resolved and the api script won't have been loaded.


Now the question is that what's the solution. You can either implement a directive that initially resolves the APIKey model and then appends the script tag into your HTML, or use the hard coded value as you use it right now (i have usually seen it hardcoded in most of the code and examples i've seen). NOTE: even if you implement such directive, you have to make sure that you are using the google maps api AFTER your directive has executed and you've got the maps api loaded.

Hope this helps.

Muhammad Ahsan Ayaz
  • 1,867
  • 10
  • 12