AngularJS:过滤器数组

时间:2014-08-01 17:16:06

标签: javascript angularjs

我为包含数据的表创建了一个元素指令。该表使用ng-repeat来呈现所有行/列。

我为element指令创建了一个属性指令。它的目的是获取您不希望包含在表中的列。完整的指令可能如下所示:

<extended-table exclude="columnone, columntwo"></extended-table>

该表被解释为:

<table>
    <tr>
        <th ng-repeat="column in columns">
        {{column}}
        </th>
    </tr>
    <tr ng-repeat="row in data | startFrom:currentRow">
        <td ng-repeat="column in columns">
            {{row[column]}}
        </td>
    </tr>
</table>

ng-repeat中,我希望忽略排除中的值,但我在这里的位置有点丢失。

app.directive('exclude', function () {
    return function (scope, element, attrs) {

        var params = attrs.exclude.split(',');

        for (var i = 0; i < params.length; i++) {
            params[i] = params[i].trim();
        }

        scope.exclude = params;
    };
});

如果列包含在ng-repeat数组中,我如何为标题和行创建$scope.exclude ignore列?

app.filter('startFrom', function () {
    return function (input, start) {
        start = +start;
        return input.slice(start);
    };
});

1 个答案:

答案 0 :(得分:1)

我的建议是通过exclude指令读取extended-table属性,而不是创建自定义指令来执行此操作。

以下是一些不完整的代码,展示了如何做到这一点:

myModule.directive('extended-table', function() {
    return {
...
      scope: {
        'exclude': '@' // This says to load the attribute 'exclude' into a scope property of the same name.
      }
...
    // In your link functions you could process the scope.exclude property as you wish.
    };
  });

可以在The Hitchhikers Guide to the Directive找到更多信息:

@ – binds the value of parent scope property (which always a string) to the local scope. So the value you want to pass in should be wrapped in {{}}. Remember `a` in braces.
= – binds parent scope property directly which will be evaluated before being passed in.
& – binds an expression or method which will be executed in the context of the scope it belongs.

这种方法的最大优点是你不会创建两个依赖于彼此的指令。

注意:

使用@进行绑定时,请记住使用{{}}表示法传递属性:

    <myDirective myDirectiveAttribute="{{someProperty}}"/>