Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  117] [ 4]  / answers: 1 / hits: 11382  / 10 Years ago, tue, august 12, 2014, 12:00:00

I have a table with a directive on it. When I sort the table then my directive is triggered which gives me a property called $elem.



This property holds the table DOM elment. Is there a way to iterate through this object and read all the <td> innerHTML of each <tr> row?



For example in this example: http://plnkr.co/edit/eodM0kMxZukG8y9DIh00?p=preview



How can I get all the TD values or each row and store that in a JS array using AngularJS only?
So the result is something like:



var arr = {['1', 'User 1', '<a href=#>link 1</a>'],
['2', 'User 2', '<a href=#>link 2</a>']};

More From » angularjs

 Answers
17

OK, I literally hate myself for saying this (grin) because this type of question is almost always the lead-in to using the wrong pattern to do something more sophisticated in AngularJS. BUT, since it does get asked a lot, this does totally work:



http://plnkr.co/edit/XnT5tGjeDUVGHJ3pzFpc?p=preview



var entries = [];
angular.forEach($elem.children()[1].children, function(tr) {
var entry = [];
angular.forEach(tr.children, function(td) {
entry.push(td.innerHTML);
});

entries.push(entry);
});
console.log(entries);


There's nothing really Angular-ish about this. $elem is just a lightweight wrapper around the HTML element for the table. It's HTML5 so there's a <thead> element followed by a <tbody>, which the first forEach follows down the chain to get each <tr> - the children of the <thead>. The inner


[#43173] Monday, August 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;