Angular filter name as variable

I am developing a generic table that reads data and columns from ajax. The column description also has the filter name that angular should use for a specific column. But in HTML templates, I cannot use variables for filter names: / Is there a solution for this? Or should I code a javascript loop with a data source?

Here's some sample code:

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

      

+3


source to share


2 answers


You cannot do this 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



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

      

using

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

      

+7


source


For those who want to do something like

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

      

where ngFilter can contain some parameters separated by colons like



currency:"USD$":0

      

In the end I wrote this little helper

function applyFilter (model, filter){
    if(filter){

        var pieces = filter.split(':');

        var filterName = pieces[0];

        var params = [model];

        if(pieces.length>1){
            params = params.concat(pieces.slice(1));
        }

        return $filter(filterName).apply(this,params);
    }else{
        return model;
    }
}

      

0


source







All Articles