angularjs - 在angularjs中使用ngMap模块es6类时,使用 'this'时 'places-auto-complete'未绑定(bind)到构造函数

标签 angularjs google-maps ecmascript-6 ng-map

我在执行 ngMap 时将 AngularJS 与 ES6 结合使用谷歌地图的自动完成功能模块。

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

})();

返回的对象: Image showing 'this' context; which is causing 'this.map' to be undefined

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

最佳答案

我的解决方案是:

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


}

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

关于angularjs - 在angularjs中使用ngMap模块es6类时,使用 'this'时 'places-auto-complete'未绑定(bind)到构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902310/

相关文章:

javascript - 我可以将数组解构和 .trim() 结合起来吗?

javascript - AngularJS 将数组转换为 JSON

javascript - 等到对象创建 - (JavaScript/AngularJS)

javascript - 多个谷歌地点请求功能(药房定位器)

javascript - 如果我的页面上有 Google map ,如何在其周围绘制一个半径为 "circle"的蓝点?

google-maps - 谷歌地图 : open InfoWindow on mouseover, 点击关闭并重新打开

javascript - 使用 AngularJS $http 服务和 Coinbase API 的 MIME 类型检查错误

javascript - 有没有办法用 CSS 在光标和输入中的占位符文本之间添加空格?

javascript - 如何使用 .env 文件在 vanilla javascript 中添加 api key

javascript - 如何在 n 秒后停用 MutationObserver?