2016-08-02 108 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