1
data = {key:0, Name:"Arun", key:1, Name:"Ajay", key:3, Name:"Ashok"}

function dynamicfilter(data, fieldName, filtervalue){
    $filter('filter')(data, { fieldName: filtervalue });
}

How to do the dynamic filter in AngularJS. I tried like this it's not working.

But If I give field name static like

 function dynamicfilter(data, filtervalue){
        $filter('filter')(data, { Key: filtervalue });
    }

It's working. May I know how set dynamic field filter inside controller in AngularJS?

2
  • Typo there: Key in dynamicfilter() should be key, all lowercase. Commented Mar 22, 2016 at 14:22
  • I think what Suresh is asking is how to pass in a property name to dynamically filter an array of objects on that property. Commented Mar 22, 2016 at 14:23

3 Answers 3

3

To make use of your dynamic property name, try using the property accessor with square brackets like obj[propertyName] = value:

function dynamicfilter(data, fieldName, filtervalue){
    var filter = {};
    filter[fieldName] = filtervalue;
    $filter('filter')(data, filter);
}

As of ES2015, you can also use computed property names. This may not work in all browsers though:

 $filter('filter')(data, { [fieldName]: filtervalue });
Sign up to request clarification or add additional context in comments.

3 Comments

inside { [fieldName]: filtervalue } having dynamic key like [fieldName] will work? I doubt about that
@PankajParkar this is a new feature Computed Property Names of ES2015, I also added a link to mdn for reference, have a look at it here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
OMG!! thats nice.. I was thinking in C# way :( +1
0

Using another syntax will let you do this:

var filterData = {}, key = 'myField', value = 'myValue';
filterData[key] = value;

Result: { myField: 'myValue' }

Comments

0

you can use somthing like this

<input type="text" [(ngModel)]="search1" value="" class = "form-control" id = "search" />

<ng-container *ngFor="let app1 of apps">
      <tr  *ngIf="!search1 || app1.name.includes(search1)">
         <td>{{app1.name}}<td>
          <td>{{app1.login}}<td>  
      </tr>
    </ng-container>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.