ps0604
ps0604

Reputation: 1071

Looping through children of DOM element in directive

In this plunk I have a directive that appends elements to the DOM. When I try to use children() in a loop I get an exception that forEach is not a function. Since children() returns an array I expected this to work. How to get the children?

Javascript:

directive.link = function (scope, element, attrs) {

    var wrap = angular.element('<div id="wrap"></div>');
    var wrapc = $compile(wrap)(scope)
    element.append(wrapc); 

    var node1 = angular.element('<div id="node1"></div>');
    var node1c = $compile(node1)(scope)
    wrapc.append(node1c);

    var node2 = angular.element('<div id="node2"></div>');
    var node2c = $compile(node2)(scope)
    wrapc.append(node2c);

    var children = wrapc.children();
    children.forEach(function(elem){  // <-- this doesn't work
        console.log(elem.attr('id'));
    });

};

Upvotes: 1

Views: 2779

Answers (2)

M22an
M22an

Reputation: 1292

The jQuery method .attr() was throwing the exception, I was able to fix it by changing it to use .id from javascript.

Updated plunker: http://plnkr.co/edit/OT0fSnryaY7A4hmeZLj9?p=preview

Upvotes: 1

gianni
gianni

Reputation: 1357

I don't know if that's what you need to achieve, but I would write it like this:

var children = wrapc.children();
angular.forEach(children, function(value, key){
    console.log(children[key].id));
});

Upvotes: 3

Related Questions