我有一个Angular控制器显示谷歌地图(通过NgMap)。在地图上,我可以通过点击地图添加标记。单击时,将在该位置设置标记并打开infoWindows。该窗口包含指向javascript函数的链接。
我的问题是,只要我的函数(goto
)在我的角度控制器之外,我才能使它工作。但我需要在goto function
中引用一些角度方法和属性(如$ scope等)。
我错过了什么?
我的代码:
(function () {
'use strict';
myApp.controller('myController', function myController($scope, $http, $window, NgMap) {
var vm = this;
NgMap.getMap({ id: 'myMap' }).then(function (map) {
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: 'myid'
}
map: map,
suppressInfoWindows: true
});
layer.addListener('click', function (e) {
var marker = new google.maps.Marker({ position: e.latLng, map: map });
map.panTo(e.latLng);
windowControl(e, infoWindow, map, marker);
});
});
function windowControl(e, infoWindow, map, marker) {
geocoder.geocode({ 'latLng': e.latLng },
function (results, status) {
var location;
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
location = results[0].formatted_address;
var windowcontent = location + "<br/><br/>";
windowcontent += "<button data-latlng='" + e.latLng + "' data-location='" + location + "' onclick='goto(this);'>GO</button>";
infoWindow.setOptions({
content: windowcontent
});
infoWindow.open(map, marker);
} else {
location = "No results";
}
} else {
location = status;
}
});
}
});
})();
function goto(thisObj) {
var latLng = thisObj.getAttribute( "data-latlng" );
var location = thisObj.getAttribute( "data-location" );
console.log(latLng + ' - ' + location);
}
答案 0 :(得分:2)
onclick="goto()"
期望全局(!)函数。如果您在控制器中定义它,它不是全局的。您可以先声明一个全局变量,然后为其指定一个函数表达式:
//Data
var cities = [
...
];
var goto; //<-- make goto global!
//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {
...
goto = function() { //<- assign the function created within the controller
alert('goto called');
}
答案 1 :(得分:0)
您可以从普通javascript中获取$scope
个变量,也可以更改其值。
//get the $scope by adding a 'class' selector, that exists into your controller template.
var myScope = angular.element($(".anyclass-Selector")).scope();
//change $scope value and call $apply to update the value to the controller
myScope.$apply(function () {
myScope.vm = 'test'; //assign $scope.vm new value
});
您可以更改路线并添加参数,例如:
$state.go('floorplan', {
'activeEventId': result.data.newEvent,
'activeHallId': result.data.hall1,
'activeHallVariant': 0
});
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = {Page: page, Url: url};
history.pushState(obj, obj.Page, obj.Url);
} else {
window.location.href = "homePage";
// alert("Browser does not support HTML5.");
}
}
ChangeUrl('Page1', 'homePage');