Filtering specific object keys in AngularJS

My webpage utilizes a data object filled with information, but I need a way to filter this data within a specific section. I want to create an input field that filters through the data based on certain fields, rather than searching all the data in the object.

To demonstrate, I have created a quick example here

    <div ng-init="friends = [{
    random:{
        tv: 'bbc'
    },name:'John', phone:'555-1276'},
      {random:{
          tv:'bbc'},name:'Mary', phone:'800-BIG-MARY'},
      {random:{
          tv:'itv'},name:'Mike', phone:'555-4321'},
      {random:{
          tv:'itv'},name:'Adam', phone:'555-5678'},
      {random:{
          tv:'itv'},name:'Julie', phone:'555-8765'},
      {random:{
          tv:'itv'},name:'Juliette', phone:'555-5678'}]"></div>

  Search: <input ng-model="searchText">
  <table id="searchTextResults">
    <tr><th>Name</th><th>Phone</th></tr>
    <tr ng-repeat="friend in friends | filter:searchText">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
    </tr>
  </table>

I have introduced a key called random, which includes a tv value like bbc. Currently, entering bbc in the search field displays all results, but my goal is to only search by name and/or phone.

Any assistance on achieving this would be highly appreciated.

Answer №1

One potential solution would be to develop a custom filter, as it seems that the default filter does not support using the logical OR operator for multiple keys.

angular.module('app',[]).filter('customFilter', function(){
     return function(input, searchText){

       if(!angular.isArray(input)) return;

       var exp = new RegExp(searchText, 'ig');
       return input.filter(function(inp){
          return exp.test(inp.name) || exp.test(inp.phone);
       });
     }
  });

Check out Plnk1 for an example

Alternatively, you could create a more versatile filter where you can specify which keys to search for:

  angular.module('app',[]).filter('customFilter', function(){
     return function(input, searchText, fields){

       if(!angular.isArray(input)) return;

          var exp = new RegExp(searchText, 'ig');
          fields = fields.split(',');

          return input.filter(function(inp){
            return fields.some(function(key){
              return exp.test(inp[key])
            });
          });
       }
  });

You can then use this filter by specifying the keys to search for:

<tr ng-repeat="friend in friends | customFilter:searchText:'name,phone'">

See Plnk2 for an implementation example

If you encounter any compatibility issues, you may need to consider using a polyfill for Array.prototype.some. Check here for more information.

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

React utilizes an array queue of objects to send data once a connection becomes accessible

I've encountered the following JSX code: import React, { Component } from 'react'; import axios from 'axios'; import serialize from 'form-serialize'; var a = [], b= []; class Form extends Component { constructor(p ...

Dragging and dropping files into the input field is not functioning properly

I've created a form where users can upload files, and I wanted to incorporate a drag-and-drop feature. Here's how I implemented it: <small id="filename"></small> <div class="dropzone" id="droparea"> <div class="input-con ...

Is it possible to send information via the URL while using jQuery Mobile?

My mobile application utilizes an in-app browser to send information, such as deviceID, to my server via a URL. For instance, the browser opens a web-page (jquery Mobile): www.myserver.com/doWork.html#deviceID Within the doWork.html file on the server si ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

"Utilizing Node's createWriteStream method in Grunt's package

Lately, I've been experimenting with using node to update the contents of html files at the end of a template file in my Grunt setup. However, I'm encountering some challenges: Here is the code snippet I'm using to add the package.json ver ...

Filter in AngularJS to display a different value retrieved from the database depending on the current iteration value

I am in the process of migrating an existing Laravel (and jQuery) application to Angular/Laravel. Here is a snippet from my code: <td>{{ Person::byId($record->id) }}</td> During my iteration, I called a function to retrieve a name based o ...

JavaScript functions are experiencing issues when used within the document.ready() function

I am facing an issue where adding a second function in JavaScript causes it to stop working on my page. Could someone help me identify the possible error? Your assistance would be greatly appreciated. It's worth noting that when I comment out the sec ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

Retrieve the personalized data-* attributes from a specific item within an array

I'm struggling to find the correct syntax for accessing custom data-* attributes for list elements within an unordered list that has been sorted and converted into an array using the following code: $("#gridlist").sortable("toArray"); The list eleme ...

Is there a way to export a single page in NextJS?

How can I create a build and export a specific page in NextJS? For example, I would like to have only one specific HTML page in the "out" directory as a result. ...

The dropdown value is limited to storing data up to the specified space

I am facing an issue with storing data selected from the second dropdown in my form. The first dropdown is for selecting the Brand Name of a car, and the second dropdown retrieves data from the database based on the brand name selected. I have used a div t ...

Codeigniter and jQuery seem to be having trouble passing all the values from JavaScript to the view

Looking to transfer all values from my JS file to the view. Currently, only one result is being passed. For instance, I have data for question 1, answer1, question 2, answer2, but only question 2 and answer 2 are being displayed in the view. Can someone as ...

Executing unique calculations on Kendo UI Grid Columns

For experienced users, this may seem simple, but as a newcomer, I'm struggling with a basic arithmetic task. I want to multiply one of the column values (DealValue) by 0.05 in my Kendo grid setup. Despite looking through the Kendo docs, I couldn' ...

Stubbing out a module's function with Sinon

Let's envision a scenario where there is a file present: // app.js const connection = require('./connection.js') module.exports = function (...args) { return async function (req, res, next) { // code implementation ... const ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

struggles with integrating arrays into object attributes in JavaScript

When working with object attributes, keep in mind that they only hold the first element of the assigned value let groupedDepActivities=[] groupedDepActivities.push({ id:1, term_activity:{ terms:[{id:1},{from:'her ...

Tips for eliminating stuttering when fixing the position of an element with JavaScript

I am currently facing an issue with a webpage I created where the text freezes when scrolled down to the last paragraph, while the images continue to scroll. Although my implementation is functional, there is noticeable jankiness when using the mouse wheel ...

What is the best approach to combine 'v-for' with 'v-if' in my code?

I have a challenge with two tables - one for books and the other for stock. I am attempting to retrieve books by their name and display them in the stock table. The code snippet I've used below is resulting in an error message being displayed. [v ...

Having trouble determining the height of multiple divs on jsPDF when creating multiple pages

I am encountering a challenge while attempting to create a pdf from html divs that have varying dimensions. The code snippet provided below illustrates the process. let pages = this.rootDataContainer.nativeElement.getElementsByClassName('pdfpage&apos ...