Tips for building a dynamic filter in AngularJS

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

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

Having trouble implementing a dynamic filter in AngularJS? I've encountered an issue where setting the field name as a variable doesn't work. However, when statically assigning the field name like this:

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

It works perfectly fine. Can anyone guide me on how to set up a dynamic field filter inside a controller in AngularJS?

Answer №1

If you want to utilize a dynamic property name, consider using the property accessor with square brackets such as obj[propertyName] = value:

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

In ES2015, there is an option to use computed property names. It's worth noting that this approach may not be supported in all browsers:

 $filter('filter')(data, { [fieldName]: filterValue });

Answer №2

Implementing a different format allows you to achieve the following:

let myFilter = {}, category = 'itemType', description = 'electronics';
myFilter[category] = description;

Outcome: { itemType: 'electronics' }

Answer №3

Here is an example of how you can implement 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular dropdown tooltip for overflowing text

Here is the select element in question: <select id="select-full" title="Make selection" class="form-control form-custom input-sm" name="Select" ng-model="form.select" ng-options="select.displayName as select.text for select in selec ...

Exploring the connection between Django and AngularJS: delving into the router functionality and how Django variables are assigned

As a beginner in IONIC, AngularJS, and Django, I recently attempted to host an IONIC project within Django. While both Django and AngularJS are excellent frameworks individually, integrating them has left me feeling confused. Question 1: How can I effecti ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Tips on passing methods to form provider with unique name for managing nested forms

As discussed in #60277873, when creating nested forms, it is necessary to rename the methods of the nested form as follows: const { register, formState: { errors }, handleSubmit, } = useForm({ mode: "onBlur", }); This code sh ...

Error encountered while attempting to install ungit on Windows XP: Unable to locate file directory in C:/Documents

Ungit seems like the ideal tool to gain a better understanding of git, thanks to its graphical interface that simplifies the process. I came across this video explanation which is very helpful in grasping how git functions, even if you don't intend to ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

What is the best way to check the difference between the current date and time with another date and

Seeking assistance in comparing 2 dates using JavaScript has been a bit challenging for me. I haven't found the exact solution on this platform yet. As a beginner in JavaScript, I initially assumed that obtaining the current date and time would be a s ...

Adding a simulated $state object to an angular unit test

I'm facing some challenges with Angular unit testing as I am not very proficient in it. Specifically, I am struggling to set up a simple unit test. Here is my Class: class CampaignController { constructor($state) { this.$state = $state; ...

React beautiful dnd and Material UI list encountering compatibility problem

I recently encountered an issue while using react beautiful dnd to create a rearrangeable Material UI List. Everything was working correctly, except for the ListItemSecondaryAction within the list. When dragging a list item, the ListItemText and ListItemIc ...

Having trouble getting Laravel Full Calendar to function properly with a JQuery and Bootstrap theme

Using the Laravel full calendar package maddhatter/laravel-fullcalendar, I am facing an issue where the package is not recognizing my theme's jQuery, Bootstrap, and Moment. I have included all these in the master blade and extended it in this blade. ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...

When you access the `selectedIndex` property in JavaScript, it will return an object of type `HTMLSelect

I am currently working on a piece of code that retrieves the value from dropdown list items and then displays it in the document. To proceed, please select a fruit and click the button: <select id="mySelect"> <option>Apple</option ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

How can I automatically direct my NodeJS application to the login screen?

Here is the setup of my project structure: There is a simple folder called static, within which I have: index.html (the homepage for user registration) login.html (the login page) In the parent folder, there is a file named server.js: // NodeJS code for ...

What is the best way to check if a function has been successfully executed?

When working with PDF documents, I often use an instance of pdfkit document known as doc: import PDFDocument from 'pdfkit' const doc = new PDFDocument() This doc instance is then passed into a function called outputTitle: export const outputTi ...

Exploring ways to locate a specific text within a URL using nodeJS

Here is a simple code snippet with a problem to solve: var S = require('string'); function checkBlacklist(inputString) { var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"]; var found = false; for (var i = 0; i < b ...

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

The Chrome extension functions properly when the page is refreshed or loaded, but it does not work with internal navigation

When landing on a YouTube page starting with w*, I have a script that triggers an alert with the URL. However, this only works when entering the page directly or upon refreshing. I am trying to make the alert trigger when navigating internally to that page ...