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

AngularJS id attribute in the included HTML template

本文关键字:AngularJS id 属性 HTML 包含      更新时间:2023-09-26

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

例如:

索引.html文件 :

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

脚本.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 );

地铁地图.html文件 :

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

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

尝试在指令的link()函数中设置映射。另外,看起来您可以使用DOMElement Map.render(),而不需要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]);
            }
        };
    });

将地图访问代码放在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);