Retrieve the auto-filled value from the input field within the controller

Here is the code snippet from my view:

<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, airport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, airport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">

I'm utilizing the Google Maps API to enable autocompletion in the input fields. This means that when a user starts typing "Lo", they will see a list of places starting with "Lo" and can choose a specific location like London.

However, I am facing an issue in my controller where I only get the initially entered value and not the complete autocompleted value. For example, I only receive "Lo" instead of "London".

Below is my controller snippet:

app.controller('BookingsCtrl', function($scope, BookingsService) {
  $scope.pickup = "";
  $scope.destination = "";
  $scope.syncNotification = "";

  $scope.calcPrice = function() {
    console.log($scope.pickup);

    BookingsService.save({
      pickup: $scope.pickup,
      destination: $scope.destination
    }, function(response) {
      console.log(response.message);
    });
  };
});

Additional details - JS snippet:

var pickup = document.getElementById('pickup');

var options = {
    componentRestrictions: {
        country: 'ee'
    }
};

var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);

google.maps.event.addListener(autocompletePickup, 'place_changed', function () {

    var place = autocompletePickup.getPlace();
    pickup.innerHtml =  place.formatted_address;
    var lat = place.geometry.location.lat();
    var long = place.geometry.location.lng();

});

Update - Added service:

app.service('BookingsService', function ($resource) {
  return $resource('http://localhost:3000/', {});
});

Update - Template:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="assets/css/style.css" type="text/css" />
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
     ></script>
</head>
<body ng-app='strelsau_client'>
  <div class="site-wrapper">
     <div class="site-wrapper-inner">
        <div class="cover-container">
           <div class="masthead clearfix">
              <div class="inner">
                 <img class="masthead-brand" src="../assets/img/logo.png">
                 <nav>
                    <ul class="nav masthead-nav">
                       <li class="active"><a href="#">Home</a></li>
                       <li><a href="#">Contact</a></li>
                    </ul>
                 </nav>
              </div>
           </div>
           <div ng-view>
           </div>
        </div>
     </div>
  </div>
  <script src="components/jquery/dist/jquery.min.js"></script>
  <script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
  <script src="components/angular/angular.min.js"></script>
  <script src="components/angular-route/angular-route.min.js"></script>
  <script src="components/angular-resource/angular-resource.min.js"></script>
  <script src="js/main.js"></script>
  <script src="js/controllers/bookings_controllers.js"></script>
  <script src="js/services/bookings_service.js"></script>
</body>
</html>

Answer №1

It turns out that the pickup input element is not being updated once the location is resolved.

The issue lies within this function:

google.maps.event.addListener(autocompletePickup, 'place_changed', function () {

    var place = autocompletePickup.getPlace();
    pickup.innerHtml =  place.formatted_address; //invalid
    //...
});

To set the value of an input field, the value property should be used instead.

For example, you can replace it with:

(function (scope) {
            google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
                var place = autocompletePickup.getPlace();
                scope.pickup = place.formatted_address;
            });
        })($scope);

Example

angular.module('myApp', [])

    .controller('BookingsCtrl', function ($scope) {

        $scope.pickup = "";
        $scope.destination = "";
        $scope.syncNotification = "";

        var pickup = document.getElementById('pickup');

        var options = {
            componentRestrictions: {
                country: 'ee'
            }
        };
        var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);

        (function (scope) {
            google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
                var place = autocompletePickup.getPlace();
                scope.pickup = place.formatted_address;
            });
        })($scope);

        $scope.calcPrice = function () {
            console.log($scope.pickup);
            alert($scope.pickup);

            /*BookingsService.save({
                pickup: $scope.pickup,
                destination: $scope.destination
            }, function (response) {
                console.log(response.message);
            });*/
        };
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
        <label for="txtFrom">Pickup Location</label>
        <input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
        <label for="txtDestination">Destination</label>
        <input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
        <input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
    </div>

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

What is preventing me from injecting a directive into my test cases?

While I have been successful in injecting various things in the beforeEach(inject(beforeEach(inject(function(_$controller_,_mycustomService_,_$log_) in Jasmine, there is one challenge I'm facing when trying to inject a directive. Despite being able ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

What is the best way for my web application to interface with a serial port?

I am working on a cloud-based web application that uses ASP Web API and Angular, both hosted on Azure. I have a requirement for my Angular app to communicate with a serial port for reading and writing data. How can I achieve this functionality? I've ...

The performance of HTTP requests is significantly decreased in Internet Explorer compared to expected speeds

I am currently developing an Angular site where I need to send a significant amount of data (approximately 1 MB) in an API call. In the Chrome and Firefox browsers, everything works smoothly and quickly, with a response time under one second. However, whe ...

ng-model is not defined when used with ng-if, but it functions properly with ng-show

I've encountered an issue with my basic functionality where I am trying to retrieve the text value on a click event. There is a text box inside an ng-if directive, but when attempting to get the value, it returns 'undefined'. After some rese ...

I am facing an issue with the AngularJS filter not functioning properly with nested JSON key/value objects

Seeking assistance with filtering JSON data based on the code/desc in the state property. Here is an example of my JSON data: $scope.agent = { "0d297c1711de": [{ "applicationName": "rewards-accounts", "agentId": "0d297c1711de", "st ...

When the scope changes, the AngularJS variables in the view are not updating accordingly

Recently diving into AngularJS has been quite the journey for me. However, I've hit a major roadblock that's had me stumped for the past two days. Here's my dilemma: Despite updating the variable in the controller, my view refuses to reflec ...

Limitation on calling $http.get() multiple times is in place

Complete Rewriting Of Inquiry The situation has taken a new turn, prompting me to clarify the current scenario from scratch. My goal is to develop a straightforward message board using Node, Express, MongoDB, and Angular. On the server side, my get and ...

Having trouble getting the ionic lib update command line to work properly?

My current situation: $ionic lib update you sure you want to replace D:\Projects\cda-volunteer\www\lib\ionic with an updated version of Ionic? (yes/no): yes Unable to receive version data Here's my ionic info: Cordova ...

Show items from nested ng-repeat within a Bootstrap carousel

Seeking advice on selecting a random item from a nested ng-repeat and incorporating it into a bootstrap carousel. Take a look at my scenario: var products = [{ "title" : "First product", "comments" : [ { "body" : "1 comment", "aut ...

AngularJS utilizes the trustAsHtml function to enable the inclusion of specific portions of a string

In the database, I have notification data that reads: Someone has recently interacted with your post. However, I need to display the username in bold using trustAsHtml. But what if the username is: alert('xss'); This would result in the outpu ...

Steps for transferring data from a POST response to the client in NodeJS/ExpressJS

I am currently in the process of setting up an EasyPost API and I need to save some data that is included in a response from a POST route. My goal is to send this data directly to the client for storage, but I am struggling to determine where or how to do ...

Error encountered while rendering ngMessages error in AngularJS due to ngif markup issue

I am currently utilizing ngMessages to validate a dynamically generated form using ngRepeat. While ngMessages is functioning as expected, I want the validation error messages to only display when the submit button is clicked. To accomplish this, I am emplo ...

Rendering nested rows in Angular datatables

How can nested tables be better displayed in angular-datatables? One solution involves using rowCallback and setting up click events: $scope.dtOptions = DTOptionsBuilder.fromSource('data.json') .withOption('rowCallback', rowCallbac ...

Enhancing User Experience with Dynamic Table Layout in Angular

I need to create a table with the following object: this.customer = [{ cid:"1", productid:"1", src:"walmart", total:"1" }, { cid:"1", productid:"1", src:"target", total:"2 ...

Transfer parameters between controller and service using Angular

I have a unique service that performs an HTTP call and retrieves data from a specific URL. My goal is to pass an argument from the Controller to the Service and use it as a parameter in the URI. For instance, my current request is api.myurl.com/foo and I ...

Discover the chosen image displayed within an ng-repeat showcased in a separate container

I am facing an issue with a table that uses ng-repeat to display data. One of the columns contains photos. When I edit a specific entry in the table, I want the corresponding photo to be shown. How can I achieve this? The code for my table looks like this ...

Angular-material's Md-dialog popup box is displayed as a separate view within the Yeoman framework

I have recently created a project using Yeoman (angular-fullstack, angular-material) and encountered an issue with triggering the md-dialog box. When clicking on a div element, the dialog box is supposed to appear. However, instead of showing the popup the ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...