3

我将 AngularJS 与 ES6 一起使用,同时实现ngMap模块以实现谷歌地图的自动完成功能。

/* 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>

以及包含组件的 javascript 文件

'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
});

})();

返回的对象返回: 显示“this”上下文的图像;这导致“this.map”未定义

我希望“ this.map ”和“ this.place ”引用构造函数属性和“ this.getPlaced () ”来获取自动完成数据。我怎么解决这个问题?

4

1 回答 1

2

我的解决方案是:

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);
  }


}

我知道一个函数必须在构造函数之外,但它对我有用。

于 2016-11-04T10:00:33.073 回答