3

I have the following:

app.directive("myDirective", function($compile) {
    return {
        replace: true,
        scope: {},
        template: "<div></div>",
        link: function(scope, elem) {

            scope.list  = [1, 2, 3, 4, 5];
            $compile("<div my-list></div>")(scope, function(clone) {
                // Why the ng-repeat isn't compiled yet?
                alert(clone[0].outerHTML);
                elem.html(clone);
            });
        }
    };
});

app.directive("myList", function() {
    return {
        replace: true,
        template: "<ul><li ng-repeat=\"item in list\">{{item}}</li></ul>"
    };
});

<div my-directive></div>

Can someone tell me why my <li>'s are not at my alert?

http://jsfiddle.net/AlexFigueiredoo/jNceZ/

hasser
  • 1,066
  • 1
  • 13
  • 24

3 Answers3

4

Here is your updated Fiddle

It's working using the $timeout directive (http://docs.angularjs.org/api/ng.$timeout) with a '0' cooldown. Sounds a bit tricky but...

So, inject $timeout in your controller, then in your callback :

$timeout(function () {
    alert(clone[0].outerHTML);
}, 0);
meriadec
  • 2,953
  • 18
  • 20
  • 2
    I think the OP was interested in "Why" this is the behaviour. So, why would adding a `$timeout` make a difference. – Davin Tryon Nov 28 '13 at 18:12
4

Ok, so I'm going to add a bit more to @dawuut's answer.

Wrapping the alert in a $timeout with a '0' cooldown will work because timeouts are not fired until the end of the angular $digest cycle.

So, when you are first calling alert in the parent directive, the children have not been compiled yet (they all have their own scope).

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
2

I guess your task of compiling <div my-list></div> is computed simultanously with the generation of the lis in the subdirective.

That would explain why your alert happens before the complete generation of li by ng-repeater.

Thus, a $timeout is useful in order to linearize both tasks.

The explanation of why is here: Why timeout(0) is sometimes necessary?

Community
  • 1
  • 1
Mik378
  • 21,881
  • 15
  • 82
  • 180