为great solution提供了this question,其中显示了如何使用指令显示嵌套对象的<tr>
。但是,我需要更进一步,并将嵌套对象传递给我的属性。
在下面的示例中,我已将obj
添加到我的范围,现在这些行已被obj
链接。但是,一旦我这样做它就会中断并且不会呈现任何行。我做错了什么?
我怀疑它与scope[attrs.rows]
有关,但我不是肯定的。
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' }
];
}
这是我的小提琴:http://jsfiddle.net/mattheye/uqNLH/1/
我正试图让它像这个小提琴一样工作:http://jsfiddle.net/mrajcok/vGUsu/
答案 0 :(得分:3)
而不是使用rows
,use scope.$eval
访问scope[attrs.rows]
,如下所示:
angular.forEach(scope.$eval(attrs.rows), function (row, index) {
但是,在rows
上更新MainCtrl
后,这将不更新,因为该值只读一次。
要进行绑定,您需要在$watch
上设置attrs.rows
,而不是这样:http://jsfiddle.net/uqNLH/7/