piernik piernik - 6 months ago 42
AngularJS Question

angular filter name as variable

I'm designing universal table that reads data and columns from ajax.
In columns description is also filter name which angular should use for a specific column.
But in HTML templates I can't use variables for filter names:/
Is there a solution for that? Or should I code javascript loop with data source?

Here is code example:

<tr ng-repeat="item in data">
<td ng-repeat="col in cols">
{{item[col.source]}}
<span ng-if="col.ngFilter">
{{col.ngFilter}} // ex. "state" filter
{{item[col.source]|col.ngFilter}} //is not working - is looking for "col.ngFilter" not "state" filter.
</span>
</td>
</tr>

Answer

You cannot do it in your HTML. First, you need to apply the filter in your controller.

function MyCtrl($scope, $filter) {

    $scope.applyFilter = function(model, filter) {
        return $filter(filter)(model);
    };

}

Then, in your HTML:

Instead of

{{item[col.source]|col.ngFilter}}

use

{{applyFilter(item[col.source], col.ngFilter)}}
Comments