我正在尝试使用Angular-Leaflet-Directive和来自两个不同的Angular服务的数据生成一个地图,这两个不同的Angular服务使用$resource调用web服务。这些服务返回包含经度/经度值的JSON消息,以填充地图上的标记。
但是,我无法获得使用来自服务的数据的指令。
我可以看到我的服务正在更新作用域,因此它们工作正常,如果我将值硬编码到控制器中,地图标记就可以正确呈现(例如,请参见下面的"center“)。我想要做的非常类似于这个example
下面是我的代码:
控制器:
angular.module('myDetails', ['leaflet-directive', 'shop', 'home'])
.controller('MyDetailsCtrl', ['$scope', '$routeParams', '$http', '$q', '$rootScope', 'shopService', 'homeService', function ($scope, $routeParams, $http, $q, $rootScope, shopService, homeService) {
function getShop() {
var d = $q.defer();
var shop = shopService.get({shopId: $routeParams.shopId}, function (shop) {
d.resolve(shop);
});
return d.promise;
}
function getHome() {
var d = $q.defer();
var home = homeService.get({homeId: $routeParams.homeId}, function (home) {
d.resolve(home);
});
return d.promise;
}
$q.all([
getShop(),
getHome()
]).then(function (data) {
var shop = $scope.shop = data[0];
var home = $scope.home = data[1];
var markers = {
shop: {
lat: $scope.shop.loc.coordinates[0],
lng: $scope.shop.loc.coordinates[1],
draggable: false,
message: $scope.shop.name,
focus: true
},
home: {
lat: $scope.home.loc.coordinates[0],
lng: $scope.home.loc.coordinates[1],
draggable: false,
message: $scope.home.name,
focus: true
}
};
console.log("Markers are " + angular.toJson(markers));
$scope.markers = markers;
});
$scope.center = {
lat: 53.26,
lng: -2.45,
zoom: 6
};
}]);我发现我的两个服务返回,作用域被值更新,但这并没有传递给angular-leaflet-directive。
Angular documentation on directives建议指令中的以下代码将子作用域链接到父作用域,以便同时更新它们:
scope: {
center: '=center',
maxBounds: '=maxbounds',
bounds: '=bounds',
marker: '=marker',
markers: '=markers',
defaults: '=defaults',
paths: '=paths',
tiles: '=tiles',
events: '=events'
}但它似乎对我不起作用。但是,angular-leaflet-directive path example似乎允许这样做(您可以添加标记、更改标记等)。地图会实时更新。
服务返回后,我需要做什么才能使标记出现在我的地图上?
请注意,在Stackoverflow上也有类似的问题,但这些问题的答案是将服务调用包括在指令中。我不想这样做,因为控制器提供了比直接的服务调用更多的功能,比如处理表单提交等,并且需要访问相同的数据。
发布于 2013-07-26 12:09:23
我也遇到过类似的问题。在我的例子中,我有一个绑定到控制器的div,该控制器包装了leaflet标签元素:
<div ng-controller="MapCtrl">
<leaflet id="map" class="map" maxBounds="maxBounds" defaults="defaults" center="center"></leaflet>
</div>可以想象,"maxBounds“、"defaults”和"center“的值位于父$scope中,而不是指令的$scope中。
var mapScope = $scope;
if (mapScope.defaults === null || typeof mapScope.defaults === "undefined") {
mapScope = mapScope.$parent;
}
if (mapScope.defaults === null || typeof mapScope.defaults === "undefined") {
throw new Error("Cannot find map defaults - have they been initialized?");
}发布于 2013-07-29 23:18:45
似乎解决这个问题的最简单方法是确保将以下行添加到控制器中……
angular.extend($scope, {
markers : {}
}这将设置作用域继承。我之前没有这样做,所以leaflet指令中的作用域不知道$scope.markers,因为它不存在!
https://stackoverflow.com/questions/17844963
复制相似问题