Len
Len

Reputation: 554

How to add dynamic column in ng-repeat filter

Is it possible to add a dynamic column filter:{'Is'+dType.Name:true} in ng-repeat filter?

<option ng-repeat="option in mainCtrl.Maps | filter:{'Is'+dType.Name:true}" ng-value="option.Id">{{option.Name}}</option>

Upvotes: 2

Views: 172

Answers (1)

Florian Lim
Florian Lim

Reputation: 5362

No, Angular will throw an error. But you can use a function instead and that function can work with dynamic attributes, e.g.:

<option ng-repeat="option in mainCtrl.Maps | filter:filterFn" ng-value="option.Id">{{option.Name}}</option>

And in the controller:

$scope.filterFn = function(option) {
  var propName = 'Is' + $scope.dType.Name; // assuming that dType is somewhere in the scope
  return option[propName] === true; // this replaces the shorthand filter in the ng-repeat
}

EDIT (due to additional details that were not part of the original question):

If you want to pass an additional parameter to your filter function you can use something I found in the following SO answer: How to use parameters within the filter in AngularJS?

Adapted to your case:

<option ng-repeat="option in mainCtrl.Maps | filter:filterFn(dType)" ng-value="option.Id">{{option.Name}}</option>

And in the controller:

$scope.filterFn = function(dType) {
  return function (option) {
    var propName = 'Is' + dType.Name; // dType is passed as parameter
    return option[propName] === true; 
  };
};

In short, your filter function has to return a function with the signature that is expected by Angular (function with one parameter: element of ng-repeat), but because of the wrapping it can also handle additional parameters.

Upvotes: 1

Related Questions