2016-04-27 17 views
3

我使用帶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()'來獲取自動完成數據。我怎麼解決這個問題?

+0

可能重複[依賴注入在控制器函數中未定義,而使用Angular1 + ES6,控制器作爲類](http://stackoverflow.com/questions/36252674/dependency-injections-are-undefined-in-controller- functions-while-using-angular1) –

回答

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


} 

我知道,一個函數必須是構造之外,但它爲我工作。

+0

也適用於我 – MarmaCinas

相關問題