包含的HTML模板中的AngularJS id属性

时间:2016-02-12 18:26:40

标签: javascript html angularjs

在AngularJS中,我的HTML模板无法识别我的HTML模板中的id属性。

例如:

index.html文件:

<div ng-controller="SubwayMapController">
   <div subway-map></div>
</div>

scripts.js文件:

app.directive('subwayMap', function () {
        return {
            templateUrl: 'Views/subway-map.html'
        };
    });

        map = new OpenLayers.Map("basicMap");
        var mapnik         = new OpenLayers.Layer.OSM();
        var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
        var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
        var position       = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
        var zoom           = 12; 

        map.addLayer(mapnik);
        map.setCenter(position, zoom );

subway-map.html文件:

<div id="basicMap"></div> 

当我打开索引页面时,我希望显示Openstreetmap的地图,但没有任何反应。

2 个答案:

答案 0 :(得分:3)

尝试在指令的link()功能中设置地图。此外,看起来您可以Map.render()使用DOMElement而不需要ID。

app.directive('subwayMap', function () {
        return {
            templateUrl: 'Views/subway-map.html',
            link: function(scope, element) {
              var map            = new OpenLayers.Map();
              var mapnik         = new OpenLayers.Layer.OSM();
              var fromProjection = new OpenLayers.Projection("EPSG:4326");   
              var toProjection   = new OpenLayers.Projection("EPSG:900913");
              var position       = new OpenLayers.LonLat(2.35,48.85)
                                       .transform(fromProjection, toProjection);
              var zoom           = 12; 

              map.addLayer(mapnik);
              map.setCenter(position, zoom );
              map.render(element[0]);
            }
        };
    });

答案 1 :(得分:0)

将地图访问代码放入setTimeout。您正尝试立即访问地图。 Angular尚未完成地图渲染,因此setTimeout是解决方案。

    $timeout(function(){
         map = new OpenLayers.Map("basicMap");
            var mapnik         = new OpenLayers.Layer.OSM();
            var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
            var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
            var position       = new OpenLayers.LonLat(2.35,48.85).transform( fromProjection, toProjection); //Paris
            var zoom           = 12; 

            map.addLayer(mapnik);
            map.setCenter(position, zoom );
    },10);