I am trying to initialize some data in an AngularJS directive with child elements. In this case, the <map> element is replaced with a <div> that gets hooked up using leaflet. I was trying to figure out if there is some way in the directive compile or link function to populate the markers collection from declared child elements, something like this:
<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> In the directive, I would like iterate over the <marker> elements to populate a collection. Should this happen in compile? Or, am I misguided that I can access my "fake DOM" prior to the actual template being inserted?
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). }; }); I am able to populate the markers using an ajax call, however, this technique would allow me to pre-populate the data on the server when the page is first requested.
template(andreplace: true), by the time the link function runs, the<marker>tags have been removed. That's why the link function can't find them.template(orreplace: true), otherwise the compile function will see the applied template rather than the original DOM. Inside the compile function you can usereplaceWith()when you're done modifying the DOM. Example: stackoverflow.com/a/10646761/215945