ng-repeat渲染行后,指令需要修改表

时间:2015-02-18 21:15:22

标签: angularjs

我有一个table指令,fixed-first-column,带有一个修改表行内容的链接函数。应用静态html表时,该指令有效。

但是,使用ng-repeat渲染表行时,它们不会被修改。例如:

<div class="table-responsive">
    <table class="table table-bordered" fixed-first-column>
        <thead>
        <tr class="active">
            <th class="label-text">Performance</th>
            <th ng-repeat="t in steps">Rnd {{t}}</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-if="metadata[key].show" ng-repeat="key in keys">
            <td class="label-text">{{outcomes[key].label}}</td>
            <td ng-repeat="r in outcomes[key].results">
                <span>{{r.result}}</span>
            </td>
        </tr>
        </tbody>
    </table>
</div>

在ng-repeat呈现表行之前,如何确保我的指令不应用于表?

1 个答案:

答案 0 :(得分:1)

好的,所以你有一个包含(2)两个或更多ngRepeat个项目的指令。

传播链可能很困难,因为每个ngRepeat都有自己的范围,而它们的父级是控制器范围。您的fixed-first-column指令可能具有自己的范围,但这取决于您编写指令的方式。

因此,您可以做的一个选项是使用repeatEnd指令捕获转发器的结尾并$emit它。

app.directive('repeatEnd', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            // Use `scope.$parent.$last` if you want this directive to have an isolated scope
            if (scope.$last) {
                scope.$emit('repeat-ended', element);
            }
        }
    };
});

然后在您的fixed-first-column指令中,您可以使用$emit

捕获$on
app.directive('fixedFirstColumn', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$on('repeat-ended', function (obj, element) {
                console.log("obj", obj);
                console.log("element", element);
                // Your other code here
            });
        }
    };
});

Here is a quick fiddle example

我正在传递$emit中的元素,因为您有多个中继器,因此您知道哪一个以$on方法结束。