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

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...

Is there a way to verify if a user has selected the correct answer in a quiz program?

Here we have code segments in ajax, javascript, html, and an xml file. I'm looking to calculate the total score based on user input to determine if they selected the correct answers for a test. I've attempted to figure this out, but I'm str ...

How to Process a Stripe Payment using jQuery AJAX (JavaScript Only)

I'm in the process of creating a custom payment form for Stripe and I want to manually initiate the AJAX call to connect with Stripe. Instead of relying on a typical submit event. Unfortunately, it seems like I might be sending the request to the inc ...

Leveraging traditional code methods within AngularJs

With a multitude of older javascript functions for sign up/sign in operations through parse.com, I am considering integrating AngularJS for improved routing and other advantages. Is it feasible to establish an angular stack and encapsulate these functions ...

Tips for preventing the need to create a function within a loop

Currently, I am in the process of collecting data through REST calls. I have created a function that accesses a "directory" endpoint to retrieve a list of individuals. While I can easily obtain details about their children, I need to make individual AP ...

Guide to Saving a List in Local Storage

I have successfully created a CRUD page where users can input text and it gets added to a list. Now, I am trying to save that list in localStorage but encountering an issue where the console log is showing an empty object. Any assistance on this matter wou ...

When you hover over them, chips transform their color

I am currently using a chip in my code and I would like to change its color when the mouse hovers over it. I attempted to achieve this by using: hover:{ backgroundColor: 'red', } In addition, I incorporated const StyledChip ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

Bidirectional data flow in AngularJS Directives

In an effort to create a dynamic form with different "widgets" based on field types and parameters stored in a database, I have been exploring directives for handling layout changes in response to various scenarios. After experimenting with some examples, ...

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...

Angular encountering injector error yet still successfully returning variables

It seems like I am facing a simple problem that I might be overlooking, as I have similar functions working fine in other controllers. However, for some reason, I'm encountering this error: Error: [$injector:unpr] Unknown provider: tourinfoProvider & ...

Jpicker is renowned for its transparency feature

I am currently using the Jpicker jpicker-1.1.6.js script which can be found at Below is a snippet of my code: <script type="text/javascript"> $(function() { $.fn.jPicker.defaults.images.clientPath='/img'; var ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Nuxt 3.11 - Best Practices for Integrating the `github/relative-time-element` Dependency

I'm encountering some difficulties while attempting to integrate github/relative-time-element with Nuxt 3.11.2 and Nitro 2.9.6. This is my current progress: I added the library through the command: $ npm install @github/time-elements. I adjusted nux ...

Using JavaScript to modify a section of an anchor link attribute

I am looking to dynamically update part of the URL when a specific radio button is selected. There are three purchase links, each representing a different amount. After choosing an animal, I need to select one of the three amounts to spend. How can I modi ...

I am seeking to retrieve data from MongoDB by utilizing the limit feature, while also sending a specific query

I'm currently facing some confusion with the limit functionality in MongoDB. I want my code to specifically retrieve data for just two hotels by sending a query request from the backend. export const getHotels = async (req, res, next) => { try ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...