我有以下TypeScript代码。当我尝试在匿名函数中更改类的属性时,我不能,因为它们超出了范围。有没有办法传递它们以便可以更改?
class PositionCtrl {
//rectangles: Rectangle[];
lat: number; long: number; rad: number;
save() {
alert("Settings Saved");
}
constructor(private $scope: ng.IScope) {
var tempLat: number = this.lat = 20;
var tempLong: number = this.long = 20;
var rad: number = this.rad = 1000;
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(Number(this.lat), Number(this.long)),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true
}
var map = new google.maps.Map(mapCanvas, mapOptions)
function setRad(x) {
this.$scope.position.rad = x;
}
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(Number(this.lat), Number(this.long)),
title: 'Some location'
});
var circle = new google.maps.Circle({
map: map,
radius: this.rad,
fillColor: '#AA0000',
clickable: false
});
circle.bindTo('center', marker, 'position');
//Watches radius for changes
$scope.$watch('position.rad', function () {
circle.setRadius(Number(rad));
circle.bindTo('center', marker, 'position');
console.log("done");
});
//Watches lat and long for changes
$scope.$watchGroup(['position.lat', 'position.long'], function () {
//THIS IS OUT OF SCOPE
marker.setPosition(new google.maps.LatLng(Number(this.lat), Number(this.long)));
console.log("done");
});
//Click event
google.maps.event.addListener(map = map, 'click', function (event) {
marker.setPosition(event.latLng);
$scope.$apply(function () {
//THIS IS OUT OF SCOPE
this.lat = event.latLng.lat();
this.Long = event.latLng.lng();
})
var test: number = 0;
console.log(tempLong);
test = Number(rad);
circle.setRadius(test);
console.log(rad);
console.log(circle.getRadius());
circle.bindTo('center', marker, 'position');
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
答案 0 :(得分:2)
使用箭头功能((args) => body
)保留this
:
//Watches lat and long for changes
$scope.$watchGroup(['position.lat', 'position.long'], () => {
// OK
marker.setPosition(new google.maps.LatLng(Number(this.lat), Number(this.long)));
});