Angular Directive - Attr中的嵌套对象

时间:2013-11-21 20:35:35

标签: javascript angularjs angularjs-directive angularjs-scope

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/

1 个答案:

答案 0 :(得分:3)

而不是使用rowsuse scope.$eval访问scope[attrs.rows],如下所示:

angular.forEach(scope.$eval(attrs.rows), function (row, index) {

Working Demo


但是,在rows上更新MainCtrl后,这将更新,因为该值只读一次。

要进行绑定,您需要在$watch上设置attrs.rows,而不是这样:http://jsfiddle.net/uqNLH/7/