我有一个显示谷歌地图的指令。我正在从 rootscope 传递纬度和经度值。 map 第一次正确加载,但如果我通过 rootscope 更改纬度和经度值,它不会加载并显示空白 map 。它也不会抛出任何错误。
我的 map 指令
<map class="card map" ng-hide="{{$scope.hideMap=false;}}" on-create="mapCreated(map)"></map>
我的指令代码:
angular.module('starter.directives', [])
.directive('map', function($rootScope) {
return {
restrict: 'E',
scope: {
onCreate: '&',
},
link: function ($scope, $element, $attr) {
function initialize() {
//Need to pass value from rootscope
myLatlng = new google.maps.LatLng($rootScope.prodPositions.latitude, $rootScope.prodPositions.longitude);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($element[0], mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Pizz Hut'
});
$scope.onCreate({map: map});
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}
if (document.readyState === "complete") {
initialize();
console.log("test lat2"+$rootScope.prodPositions.latitude, $rootScope.prodPositions.longitude);
} else {
google.maps.event.addDomListener(window, 'load', initialize);
console.log("test lat3"+$rootScope.prodPositions.latitude, $rootScope.prodPositions.longitude);
}
}
}
});
最佳答案
我认为您需要监视 $rootScope.prodPositions
变量的更改,然后需要重新编译指令。
要重新编译您的指令,您需要将其添加到链接函数中:
$compile($element.contents())($scope);
并添加 $compile
服务作为 DI。
关于javascript - 在指令内使用 rootscope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231525/