openlayers的angularjs指令模板绑定不起作用

时间:2016-08-02 09:24:10

标签: javascript angularjs openlayers-3

我的角度指令是关于openlayers地图应用程序。

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

Angular 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 个答案:

答案 0 :(得分:-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>'
    }
});