2

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>
Len
  • 534
  • 1
  • 15
  • 31

1 Answers1

1

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.

Florian Lim
  • 5,332
  • 2
  • 27
  • 28
  • `dType.Name` is inside an `ng-repeat`. Since I need to pass the `dType.Name` I tried it like this `filter:{mainCtrl.getDType(dType.Name):true}`. Adding the `===true` inside the function doesn't filter it. – Len Feb 19 '19 at 10:07
  • @klent I added an option that should cover your case. – Florian Lim Feb 19 '19 at 10:58
  • I didn't add `option` in the function so it didn't work when I tried it before. It filters now. Thanks! – Len Feb 20 '19 at 00:35