triggering a method in an Angular controller using a Google API embedded in the view

Using the Google Places Details API, I have included a Google API with a callback function called initMap in the src attribute. Here is the code snippet:

<div class="tab-pane active"  id="timeline">
 <p class="lead">Location</p>
 <hr>
 <div class="row">
  <div class="col-md-1"></div>
  <div class="col-md-8">
   <h2><a href="#"></a> 
    <span>location <b style="color:black;"> kolkata</b></span></h2>
      <p></p>
      <div id="map" style="width:100%;height:400px;"></div>
      <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"></script>
     <p></p>
    </div>
  </div>
</div>

I also created the initMap function within the same HTML document:

<script>
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 22.652687, lng: 88.376882},
      zoom: 15
    });

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    service.getDetails({
      placeId: 'ChIJvYbRT7Gd-DkR6QZQfJP9ZJg'
    }, function(place, status) {
      debugger
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
            'Place ID: ' + place.place_id + '<br>' +
            place.formatted_address + '</div>');
          infowindow.open(map, this);
        });
      }
    });
}
</script>

This setup works perfectly when the function is inside a script tag. But how can I call initMap from a controller?

Answer №1

Instead of calling it in that manner, you can dynamically load the script using JavaScript within your controller once your app has loaded by utilizing document.createElement('script'). After that, attach an onload event listener and then insert it into the head tag.

Here's an example:

var script = document.createElement('script');
script.src = 'google api script';
script.onload = function () {
// your onload function
$scope.onload();
$scope.$digest();
};

document.querySelector('head').appendChild(script);

This approach grants you the flexibility to determine which AngularJS actions you wish to carry out every time the script loads. I hope this explanation is useful.

Answer №2

Creating a function within your HTML page will result in automatic assignment of the function to the window object. This is due to the default scope of scripts included on the page.

Therefore, from your controller, you can easily call the function by using: window.initMap();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dropdown menu in Vue 3: A step-by-step guide

I've scoured the entire internet, but I still can't seem to resolve this issue. When using the code below, I keep getting an error message that says 'Uncaught ReferenceError: VueSelect is not defined.' Can you help me figure out what&ap ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

Ways to display scroll bar when hovering the mouse pointer?

When visiting the website YouTube, you may notice that their sidebar scrollbar becomes visible as soon as your mouse moves over it. I've been attempting to achieve this effect on my own div, but currently, the scrollbar only appears once I start scrol ...

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

Issue: Unable to utilize import statement outside a module as per the guidelines of the vue-test-utils official tutorial

I'm struggling to get Vue testing set up with vue-test-utils and jest. I followed the installation guide at https://vue-test-utils.vuejs.org/installation/#semantic-versioning, but can't seem to figure out what's wrong. Here's what I&apo ...

Modifying the <TypescriptModuleKind> setting for typescript transpilation in project.csproj is not supported in Visual Studio 2017

I recently encountered an issue with changing the module kind used by the transpiler in Visual Studio. Despite updating the <TypescriptModuleKind> in the project's project.csproj file from commonjs to AMD, the transpiler still defaults to using ...

Simple methods to minimize the iteration of array loops in Node.js

First, retrieve the "grid_id" from the "grids" array ( Step 1 ) Next, verify if this "grid_id" is present in the "variationsDB" array ( Step 2 ) Once you have this "grid_id", use it to fetch the "var ...

Having trouble obtaining outcomes from Cloud Code in Parse

After struggling with this issue for quite some time, I have reached a point where I feel the need to seek help. I am working on a cloud code function that is supposed to retrieve a list of categories along with their respective products. Each category con ...

Creating a customized component using unique styles in Material UI version 1

Currently, I am facing a challenge in styling my Card component with a width of 75 pixels while using Redux and Material UI V1. Despite following the example provided by Material UI on custom styling through withStyles and connect, I have not been able to ...

Missing Angular reference in WordPress

Have you ever tried integrating Angular into a WordPress plugin? I recently attempted to do so by adding the following code: wp_register_script('jquery-custom', ("http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"), false); ...

What is the best method for rounding a decimal number to two decimal places?

Here is the JavaScript code I am using: $("input[name='AuthorizedAmount'], input[name='LessLaborToDate']").change(function () { var sum = parseFloat($("input[name='AuthorizedAmount']").val()).toFixed( ...

Ways to customize a directive to show conditionally with no need for container elements

I have created a basic role-based security directive in angularjs. It's my first attempt at making a directive. My goal is to replace the following HTML: <authorize if-granted="GET_POSTS"> Hello WORLD!!!! {{name}} </authorize> with j ...

Unable to transmit data to CodeIgniter controller through ajax communication

I'm struggling with sending a value from an input element to a Codeigniter controller using ajax. The problem arises because I am using a WYSIWYG editor (summernote), which only allows me to receive the input inside a <script>. However, when I ...

Difficulty in showcasing error on the website with JavaScript

I have recently developed a webpage that includes several input boxes and a submit button within a form as shown below: <form action="" method="post" name="password"> Upon clicking the submit button, a JavaScript function is triggered to validate i ...

Use AngularJS to integrate ArcGIS JS 4 API and showcase a dynamic map on your webpage

I'm just beginning to learn ArcGIS JS and I would really appreciate any assistance. My initial goal is to showcase a map using ArcGIS JS API 4 with AngularJS. Any guidance or sample code would be greatly appreciated. Thank you ...

divide a JSON list

Within this JSON array, there is a plethora of person data, each with their own specified type such as "hr" or "accounting". The structure of the JSON array is depicted below: { "0": { "id": "2", "name": "blabla", "type": "hr" ...

Scroll horizontally within the div before scrolling down the page

After reviewing other questions, it's important to note that the scroll I am looking for is horizontal, not vertical. My goal is to have a div on a page automatically start scrolling when it reaches the center or becomes visible, and then allow the pa ...

Changing the value of a JavaScript variable within the .Net Codebehind

I've run into an issue where I need to update a JavaScript variable after post-back. My initial approach was to use the ClientScript.RegisterStartupScript function, which worked fine during the first page load but failed on subsequent postbacks. I inc ...