There is great solution provided for this question, that shows how to use a directive to display <tr>
's for nested objects. However, I need to take it a step further and pass a nested object into my attribute as well.
In the example below, I have added obj
to my scope and the rows are now chained off obj
. However, as soon as I do this it breaks and doesn't render any of the rows. What am I doing wrong?
My suspicion is it has to do with scope[attrs.rows]
but I'm not positive.
HTML:
<div ng-controller="MyCtrl">
<my-table rows='obj.rows'></my-table>
</div>
Javascript:
var myApp = angular.module('myApp', []);
myApp.directive('myTable', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
var html = '<table>';
angular.forEach(scope[attrs.rows], function (row, index) {
html += '<tr><td>' + row.name + '</td></tr>';
if ('subrows' in row) {
angular.forEach(row.subrows, function (subrow, index) {
html += '<tr><td>' + subrow.name + '</td></tr>';
})
}
})
html += '</table>';
element.replaceWith(html)
}
}
});
function MyCtrl($scope) {
$scope.obj = {
rows = [];
}
$scope.obj.rows = [
{ name: 'row1', subrows: [{ name: 'row1.1' }, { name: 'row1.2' }] },
{ name: 'row2' }
];
}
Here is my fiddle: http://jsfiddle.net/mattheye/uqNLH/1/
I'm trying to get it to work like this fiddle: http://jsfiddle.net/mrajcok/vGUsu/