简体   繁体   中英

AngularJS: filter array

I created an element directive for a table with data. The table uses ng-repeat s to render all of the rows/columns.

I created an attribute directive for the element directive. It's purpose is to get the columns you do not wish to include in the table. The full directive might look something like this:

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

The table is interpreted as:

<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>

In the ng-repeat s, I would like it to ignore the values in exclude, but i'm a bit lost on where to go from here.

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;
    };
});

How would I make the ng-repeat ignore column both for the header and rows if the column is contained within the $scope.exclude array?

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

My recommendation would be to instead read the exclude attribute via your extended-table directive, rather than creating a custom directive to do it.

Here is some incomplete code showing how this could be done:

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.
    };
  });

More information can be found at 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.

The biggest advantage to this approach is that you are not creating two directives that are dependent on eachother.

Note:

When using @ to bind, remember to pass your properties with {{}} notation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM