ps0604 ps0604 - 5 months ago 6
AngularJS Question

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'));
});

};

Answer

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));
});
Comments