Javascript 包含的HTML模板中的AngularJS id属性
在AngularJS中,我的javascript无法识别HTML模板中的id属性 例如: index.html文件:Javascript 包含的HTML模板中的AngularJS id属性,javascript,html,angularjs,Javascript,Html,Angularjs,在AngularJS中,我的javascript无法识别HTML模板中的id属性 例如: index.html文件: <div ng-controller="SubwayMapController"> <div subway-map></div> </div> subway-map.html文件: <div id="basicMap"></div> 当我打开索引页面时,我希望Openstreetmap中的地图
<div ng-controller="SubwayMapController">
<div subway-map></div>
</div>
subway-map.html文件:
<div id="basicMap"></div>
当我打开索引页面时,我希望Openstreetmap中的地图会显示出来,但什么也没发生 将地图访问代码放入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);
尝试在指令的
link()
函数中设置映射。另外,看起来您可以使用DomeElement而不需要ID来Map.render()
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]);
}
};
});
我认为您必须在链接函数中编写地图代码,以便更好地使用Angular的
$timeout
,而不是setTimeout
。没有必要等半秒钟;零持续时间$timeout
足以将此代码延迟到下一个摘要循环。我是否也将此$timeout
放在关闭函数中<代码>(函数(){…})()当您可以使用ng onload=“renderMap()”
时,为什么要使用$timeout
这似乎是一种脆弱的方法。我在指令的link()
函数中设置了映射。我得到一个角度错误this.div.appendChild不是一个函数
和一个Openstreetmap错误this.div.style是未定义的
。你将不得不玩一点,没有小提琴。可能需要使用元素[0]
。已更新。好的,我尝试了元素[0]
,没有收到更多错误。但地图上没有显示。我会玩一下。谢谢@Malk,你的解决方案对我有用。我必须将css从%
更改为vw
和vh
,才能显示地图<代码>px也可以工作。
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]);
}
};
});