1

我有一個指令來顯示谷歌地圖。我從rootcope傳遞晶格和經度值。第一次正確加載地圖,但如果我通過rootcope改變晶格和經度值,它不會加載並顯示空白地圖。它也不會引發任何錯誤。在指令中使用rootscope變量

我的地圖指示

<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); 
     } 
    } 
    } 
}); 
+0

你需要重新渲染指令,或負責繪製地圖,每一次你rootScope變量的值變化的功能。 – Shivi

+0

**注意:**'ng-hide'不應該有插值,它應該是'ng-hide =「hideMap」' –

+0

@PankajParkar如何重新渲染指令? – Naju

回答

0

我認爲你需要注意變量$rootScope.prodPositions變化,然後你需要重新編譯你的指令。

重新編譯指令,你NEDD添加這個您的鏈接函數中:

$compile($element.contents())($scope);

,並添加$compile服務作爲DI。

Angular $compile

+0

如何重新編譯指令?你能給我一些參考嗎? – Naju

+0

您需要在檢測到更改後在鏈接函數中添加'$ compile($ element.contents())($ scope);'。 – Niezborala