我正在尝试在局部视图中使用 ng-map 库。它在页面的初始设置(即第一次创建局部视图时)工作正常。
但是,如果我导航到不同的局部视图(例如,通过单击我在地图上放置的标记)然后点击浏览器的后退按钮,事情就会崩溃。
地图对象似乎存在于 $scope 中,但它没有“连接”到元素。因此,例如,调用 $scope.map.getBounds() 会导致返回空值。
如果对传入 mapInitialized 事件处理程序的 map 变量调用 getBounds() 也是如此。
消除对 getBounds() 的调用——我用它来提取信息以创建标记——消除了未定义值错误。但是地图本身从未被初始化。视口只是一个大的灰色矩形。我认为这进一步证明了地图 html 元素在重新创建局部视图时没有“连接”到库代码。
app.controller("mapCtrl", function ($scope, $location, dataContext) {
$scope.markers = [];
// these bind to attributes of the map element in my html
$scope.pins = function() { return dataContext.pins(); }
$scope.center = dataContext.center();
$scope.zoom = function() { return dataContext.zoom() };
$scope.$on('mapInitialized', function(evt, map){
// this stores changes to the center of the map
// so I can recreate it when the partial view is recreated
$scope.dragend = function() {
dataContext.center(map.getCenter());
dataContext.get(map.getBounds());
}
// this stores changes to the map's zoom level
// so I can recreate it when the partial view is recreated
$scope.zoomchanged = function() {
dataContext.center(map.getZoom());
dataContext.get(map.getBounds());
}
// this is where I noticed the problem -- when
// the partial view is initially created bounds is
// defined and my marker creation routine works fine.
// but when the view is recreated upon navigating back
// to the partial view, bounds is undefined, and the
// map never displays
var bounds = map.getBounds();
if( bounds != null ) dataContext.get(map.getBounds());
});
// this is the marker click handler, which takes us to a
// different partial view
$scope.click = function() {
dataContext.pin(this.pinindex);
if( dataContext.pin().Homes.length == 1)
{
dataContext.home(0);
$location.path("/home");
}
else $location.path("/unit");
};
});
逐步执行 Map 指令初始化
当 map 指令第一次执行时(即在初始页面加载时),从 angular 传递给初始化的 attrs 对象包含一个有效的中心和缩放。
但是当该指令随后在返回页面时被初始化时(即,当重新创建局部视图时),只有缩放被正确定义。中心是“,”,没有意义。
我不确定为什么第二次忽略 center 属性值,但这似乎是问题的根源。不幸的是, attrs 设置在 angular 库中,我没有时间去探索。希望这可以帮助。