我使用帶ES6的AngularJS,同時爲谷歌地圖的自動完成功能實現ngMap模塊。在angularjs中使用ngMap模塊es6類時,'this'在使用'places-auto-complete'時未綁定到構造函數上
/* 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 causing 'this.map' to be undefined
我想 'this.map' 和 'this.place'參考構造函數屬性和'this.getPlaced()'來獲取自動完成數據。我怎麼解決這個問題?
可能重複[依賴注入在控制器函數中未定義,而使用Angular1 + ES6,控制器作爲類](http://stackoverflow.com/questions/36252674/dependency-injections-are-undefined-in-controller- functions-while-using-angular1) –