2
爲this question提供了great solution,它顯示瞭如何使用指令來顯示<tr>
的嵌套對象。但是,我需要更進一步,並將嵌套對象傳遞給我的屬性。Angular Directive - Attr中的嵌套對象
在下面的示例中,我已將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/
謝謝,這是一個很好的答案。但是,$ watch在添加新的obj.rows時似乎不會觸發。有任何想法嗎? http://jsfiddle.net/mattheye/uqNLH/4/ –
啊,的確如此。你需要深入的對象監控才能做到這一點:http://jsfiddle.net/uqNLH/7/在Angular 1.2中,'$ watchCollection'完全適合你的用例。但是,'jsFiddle'目前不允許我使用它。 –
完美,謝謝! –