2016-08-02 110 views
0

我的angular指令是關於openlayers地圖應用程序的。對於openlayers的angularjs指令模板綁定不起作用

<div ng-app="app"> 
    <map-container></map-container> 
</div> 

Working code is here

angular.module("app",[]); 

angular.module("app").controller("MapContainerController", function ($scope) { 
    $scope.map = new ol.Map({}); 
}); 

angular.module("app").directive("mapContainer", function ($timeout) { 
    return { 
     "transclude": true, 
     "controller": "MapContainerController", 
     "link": function (scope) { 
      var map = scope.map; 
      map.setTarget(scope.targetElement || "map"); 
      map.addLayer(new ol.layer.Tile({ 
       source: new ol.source.OSM() 
      })); 
      map.setView(new ol.View({ 
       zoom: 3, 
       center: [0, 0] 
      })); 
     }, 
     "template": '<div id="map" class="map" ng-transclude></div>' 
    } 
}); 

但我想使用範圍參數指示地圖元素名稱,如下面的代碼:demo version is here

<div ng-app="app"> 
    <map-container target-element="map"></map-container> 
</div> 

但這不起作用。

angular.module("app").directive("mapContainer", function ($timeout) { 
    return { 
     "transclude": true, 
     "scope": { 
      "targetElement": "@" 
     }, 
     "controller": "MapContainerController", 
     "link": function (scope) { 
      var map = scope.map; 
      map.setTarget(scope.targetElement || "map"); 
      map.addLayer(new ol.layer.Tile({ 
       source: new ol.source.OSM() 
      })); 
      map.setView(new ol.View({ 
       zoom: 3, 
       center: [0, 0] 
      })); 
     }, 
     "template": '<div id="{{targetElement}}" class="map" ng-transclude></div>' 
    } 
}); 

一切看起來很好,但它不起作用。我無法理解這個問題。

回答

-1

你只需要將你的指令代碼包裝在$ timeout中,以便在創建地圖之前使用id顯示模板。

angular.module("app").directive("mapContainer", function ($timeout) { 
    return { 
     "transclude": true, 
     "scope": { 
      "targetElement": "@" 
     }, 
     "controller": "MapContainerController", 
     "link": function (scope) { 
      var map = scope.map; 

      $timeout(function() { 
       map.setTarget(scope.targetElement || "map"); 
       map.addLayer(new ol.layer.Tile({ 
        source: new ol.source.OSM() 
       })); 
       map.setView(new ol.View({ 
        zoom: 3, 
        center: [0, 0] 
       })); 

      }); 
        }, 
     "template": '<div id="{{targetElement}}" class="map" ng-transclude></div>' 
    } 
}); 
+0

我通過目標元素屬性https://jsfiddle.net/barteloma/ywo20y2L/1/ – barteloma

+0

和我做了太多與它的工作,你可以看到它的日誌「格」 https://開頭的jsfiddle。 net/y68v64xw/ – Gatsbill

+0

控制檯將結果記錄在右側,但映射未顯示。這顯示地圖:https://jsfiddle.net/barteloma/ywo20y2L/但是這不顯示地圖:https://jsfiddle.net/barteloma/ywo20y2L/1/ – barteloma