3

I'm using AngularJS with ES6, while implementing ngMap module for the autocomplete feature of google map.

/* html file */
  Enter an address: <br/>
<input places-auto-complete size=80
       ng-model="$ctrl.address"
       component-restrictions="{country:'in'}"
       on-place-changed="$ctrl.placeChanged()"/> <br/>
<div ng-show="$ctrl.place">
  Address = {{$ctrl.place.formatted_address}} <br/>
  Location: {{$ctrl.place.geometry.location}}<br/>
</div>
address : {{$ctrl.address}}
<ng-map></ng-map>

And the javascript file containing component

'use strict';
(function() {

class RateRestaurantsController {
constructor(NgMap) {
  this.NgMap = NgMap;
  this.types = "";
  this.place = "";
  this.address = "";
  this.map = {};


}

$onInit() {

  this.NgMap.getMap().then((map)=> {
    this.map = map;
  });
}

placeChanged(){
 console.log(this); // This refers the [Object] returned by google map api; not to the the constructor(as shown in the image)
  this.place = this.getPlace();
  this.map.setCenter(this.place.geometry.location);

  }

 }

angular.module('gmHotelRatingApp.rateRestaurants')
.component('rateRestaurants', {
  templateUrl: 'app/rate-restaurants/rate.restaurants.html',
  controller: RateRestaurantsController
});

})();

The Object returned which is returned: Image showing 'this' context; which is causing 'this.map' to be undefined

I want 'this.map' and 'this.place' reference to constructor property and 'this.getPlaced()' to fetch the auto complete data. How can I solve this problem?

Kunal Sharma
  • 371
  • 2
  • 20
  • Possible duplicate of [Dependency Injections are undefined in controller functions while using Angular1+ ES6, with controller as a class](http://stackoverflow.com/questions/36252674/dependency-injections-are-undefined-in-controller-functions-while-using-angular1) – Paul Sweatte Oct 11 '16 at 14:22

1 Answers1

2

My solution is:

constructor(NgMap) {

  this.ngMap = NgMap;

  var controller = this;
  this.ngMap.getMap().then((map) => {
      this.map = map;
  });

  this.myCallback = function () {
     controller.place = this.getPlace();
     controller.map.setCenter(controller.place.geometry.location);
  }


}

I know that a function must be outside the constructor but it works for me.