答案 0 :(得分:0)
绑定getpos
事件处理程序时,函数执行的上下文将被修改,this
不再引用控制器,而是引用map对象。
您可以考虑以下选项:
一种选择是将$ctrl
属性传递给getpos
函数:
on-click="$ctrl.getpos($ctrl)"
然后latlng
属性可以像这样修改:
getpos(event,ctrl){
ctrl.latlng = [event.latLng.lat(), event.latLng.lng()];
};
演示
class Controller {
constructor() {
this.latlng = [-25.363882,131.044922];
}
getpos(event,ctrl){
ctrl.latlng = [event.latLng.lat(), event.latLng.lng()];
console.log(ctrl.latlng);
};
}
angular.module('app', ['ngMap']).component('myMap', {
template: `
<ng-map center="-25.363882,131.044922" zoom="4" on-click="$ctrl.getpos($ctrl)">
<marker position="{{$ctrl.latlng}}" title="Hello World!" on-dragend="$ctrl.getpos($ctrl)"
animation="Animation.BOUNCE" animation="DROP" draggable="true"></marker>
</ng-map>
{{$ctrl.latlng}}`,
controller: Controller
})
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="app">
<my-map></my-map>
</div>
另一种选择是引入一个保持控制器上下文的函数,例如:
class Controller {
constructor() {
var self = this;
this.bind = function () {
var args = [].slice.call(arguments);
var event = args.shift();
var fn = args.shift();
fn.apply(self, [event].concat(this,args));
};
}
}
然后绑定:
on-click="$ctrl.bind($ctrl.getpos)"
latlng
属性可以通过this
修改:
getpos(event) {
this.latlng = [event.latLng.lat(), event.latLng.lng()];
};
演示
class Controller {
constructor() {
this.latlng = [-25.363882, 131.044922];
var self = this;
this.bind = function () {
var args = [].slice.call(arguments);
var event = args.shift();
var fn = args.shift();
fn.apply(self, [event].concat(this,args));
};
}
getpos(event) {
this.latlng = [event.latLng.lat(), event.latLng.lng()];
console.log(this.latlng);
};
}
angular.module('app', ['ngMap']).component('myMap', {
template: `
<ng-map center="-25.363882,131.044922" zoom="4" on-click="$ctrl.bind($ctrl.getpos)">
<marker position="{{$ctrl.latlng}}" title="Hello World!" on-dragend="$ctrl.bind($ctrl.getpos)"
animation="Animation.BOUNCE" animation="DROP" draggable="true"></marker>
</ng-map>
{{$ctrl.latlng}}`,
controller: Controller
})
<script src="https://maps.google.com/maps/api/js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="app">
<my-map></my-map>
</div>