Miguel Péres Miguel Péres - 8 months ago 26
AngularJS Question

Get an element in DOM hierarchy from the link function of a directive [AngularJS]

I have a simple DOM hierarchy and I want to grab a specific set of elements (I want all the canvas elements). This is the entire template for this directive:

<div id='charts-container'>
<div class='chart-wrapper' ng-repeat='chart in getNumberOfCharts() track by $index'>
<canvas id="{{'exam-chart-' + $index}}" class='chart-canvas'></canvas>

I want to create a list with all the canvas within the #charts-container element, but I just can't. This is what I'm trying to do inside the link function:

link: function (scope, element, attributes, controller) {
var look = element.find('#chart-canvas');

And then I get this element, but I don't know how to get all the chart-wrapper elements from here.

I tried doing
, it returned an empty list, but at the same time showed me what I wanted as if the list were populated, here is an image. If I try to access any index of this list, it returns undefined (which is fine, because it's an empty list. But why the console is showing me these values?)

What is the best way to achieve this? To get all the canvas elements in this template? (there are 15 of them). Thanks!

--- UPDATE ---

I realized that if I remove the ng-repeat attribute I'm using in the template, it works! But I need the ng-repeat...

manage to get the canvas element, but only if there are no ng-repeat attribute.

Is this a common issue when using ng-repeat. Is there any special treatment when falling in this case?


I found a solution in this thread.

Apparently I was trying to access DOM that hasn't been rendered yet. So, wrapping my query for the canvas with

$timeout(function() {
    var canvasList = element.find('.chart-canvas');
}, 0);

solved the issue, since using $timeout will wait until all $digest cycles are complete.

I would like to get to know better how the rendering pipeline works in AngularJS, to avoid falling in issues of this kind. If anyone has a link to a thread or explanation of this, it would be much appreciated.