【发布时间】:2013-03-28 18:25:17
【问题描述】:
我正在尝试使用子元素初始化 AngularJS 指令中的一些数据。在这种情况下,<map> 元素被替换为使用传单连接的<div>。我试图弄清楚指令compile 或link 函数中是否有某种方法可以从声明的子元素中填充markers 集合,如下所示:
<div ng-app="dashboard">
<div ng-controller="DashboardCtrl">
<map id="devicemap" tile-handle="test.map-fy18v14h" min-zoom="3" max-zoom="9" markers="markers">
<marker lat="44" lng="-88.5" description="From the Server (Razor)" />
<marker lat="44.1" lng="-88.6" description="From the Server 2 (Razor)" />
</map>
</div>
在指令中,我想遍历 <marker> 元素以填充集合。这应该在编译中发生吗?或者,我是否误以为我可以在插入实际模板之前访问我的“假 DOM”?
module.directive('map', function () {
return {
restrict: "E",
replace: true,
scope: {
markers: "=markers"
},
template: '<div class="map"></div>',
link: function link(scope, elm, attributes) {
var map = L.map(attributes.id, {
dragging: true,
zoomAnimation: true
}).setView([45.505, -88.09], 6);
L.tileLayer('http://{s}.tiles.mapbox.com/v3/' + attributes.tileHandle + '/{z}/{x}/{y}.png', {
attribution: "<a href='http://mapbox.com/about/maps' target='_blank'>Terms & Feedback</a>",
}).addTo(map);
// This is where I am stuck... is there a way to get the "marker" elements?
// the following does not work...
var markerElements = elm.children('marker');
// now would like to loop over markerElements, grab the attributes and add them
// to the map (and/or the markers collection).
};
});
我可以使用 ajax 调用来填充标记,但是,这种技术将允许我在第一次请求页面时预先填充服务器上的数据。
【问题讨论】:
-
因为您使用的是
template(和replace: true),所以在链接函数运行时,<marker>标记已被删除。这就是链接功能找不到它们的原因。 -
这是有道理的。有没有办法在原始 DOM 被替换之前访问它?
-
你可以在编译函数中这样做,但你不能使用
template(或replace: true),否则编译函数会看到应用的模板而不是原始的DOM。在 compile 函数中,您可以在完成 DOM 修改后使用replaceWith()。示例:stackoverflow.com/a/10646761/215945
标签: asp.net-mvc angularjs angularjs-directive