1

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

};
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • 1
    Check if `children()` method returns a promise, I usually end up bumping into promises expecting arrays / objects. – M22an Jul 01 '16 at 11:18
  • no, it doesn't seem to return a promise – ps0604 Jul 01 '16 at 11:22
  • Hmm, Angular's documentation for that `angular.element.children()` points to the jQuery equivalent. What do you get when you log the `children` variable ? – M22an Jul 01 '16 at 11:25
  • I get the two elements, node1 and node2 in a DOM array: [div#node1.ng-scope, div#node2.ng-scope] – ps0604 Jul 01 '16 at 11:28
  • Hmm, the Node list that you get actually needs to be converted to an array, check if this helps http://stackoverflow.com/a/18129752/3131696 – M22an Jul 01 '16 at 11:35
  • The node list that I get after the conversion is the same as the original one, and I get the same error. Look at this http://plnkr.co/edit/hnrrZGpiGRdLTy8XHdup?p=preview – ps0604 Jul 01 '16 at 11:39

2 Answers2

3

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));
});
gianni
  • 1,199
  • 2
  • 14
  • 28
1

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

M22an
  • 1,242
  • 1
  • 18
  • 35