Combining Fields in Angular Filter to Enhance Search功能

I am facing a challenge with filtering a list of people based on their first and last name properties using Angular's filter functionality. The issue is that the filter only considers one property at a time, so users cannot search for both first and last names simultaneously. Is there a way to create 'virtual' properties that combine two existing properties for search purposes?

If my explanation was confusing, as it usually is, you can test it by searching for 'Steve Jobs' in the code snippet provided:

var app = angular.module('app', []);

app.controller('myCtrl', function($scope) {
  $scope.people = [
    {first: 'John', last: 'Smith'},
    {first: 'Jane', last: 'Doe'},
    {first: 'Bill', last: 'Gates'},
    {first: 'John', last: 'Krasinski'},
    {first: 'Ada', last: 'Lovelace'},
    {first: 'Brad', last: 'Pitt'},
    {first: 'Steve', last: 'Jobs'},
    {first: 'Bill', last: 'Clinton'},
    {first: 'Britishname', last: 'Complicated'},
    {first: 'Steve', last: 'Wozniak'}
  ];
});
<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="search" placeholder="Search...">
  
  <ul>
    <li ng-repeat="person in people | filter: search">
      {{person.first}} {{person.last}}
    </li>
  </ul>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Answer №1

After some investigation, I managed to solve the problem by myself. However, I decided to share my solution here to assist others. One approach is to define a filter function like the one below:

var app = angular.module('app', []);

app.controller('myCtrl', function($scope) {
  $scope.people = [
    {first: 'John', last: 'Smith'},
    {first: 'Jane', last: 'Doe'},
    {first: 'Bill', last: 'Gates'},
    {first: 'John', last: 'Krasinski'},
    {first: 'Ada', last: 'Lovelace'},
    {first: 'Brad', last: 'Pitt'},
    {first: 'Steve', last: 'Jobs'},
    {first: 'Bill', last: 'Clinton'},
    {first: 'Britishname', last: 'Complicated'},
    {first: 'Steve', last: 'Wozniak'}
  ];
  
  $scope.criteriaMatch = function(criteria) {
    return function(person) {
      var concatenated = person.first + ' ' + person.last;
      return !criteria || concatenated.toLowerCase().indexOf(criteria.toLowerCase()) !== -1;
    }
  };
});
<div ng-app="app" ng-controller="myCtrl">
  <input type="text" ng-model="search" placeholder="Search...">
  
  <ul>
    <li ng-repeat="person in people | filter: criteriaMatch(search)">
      {{person.first}} {{person.last}}
    </li>
  </ul>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

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

Guide on displaying the <html> tag within text using AngularJS

I need to display some data in HTML, which looks like this: <p>abcd efg hijk....(<a href=\"http:\/\/www.facebook.com\/stock\/NBR\">NYSE:NBR<\/a>),, however, there are some HTML tags within ...

Practicing diligently, JavaScript code snippets

In my app using Playframework 2.2, I heavily rely on ajax to load content dynamically. There are times when I need to bind or change an event handler after loading content via ajax. For example, if I want to modify the click handler for a newly retrieved ...

Utilizing Isotope JS on your Wordpress website

I'm in the process of integrating the .js plugin, Isotope, into my Wordpress installation. It should be positioned at the bottom of this page: To achieve this, I am referring to an example on codepen: https://codepen.io/desandro/pen/mEinp The script ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

Connecting the input[date] and Moment.js in AngularJS

For the purpose of formulating a question, I have prepared a simplified example: ... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', [& ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons. https://i.sstatic.net/RzagX.png When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behav ...

Is it advisable to opt for the linking function instead of the compile function in Angular whenever possible?

Recently, I delved into the intricacies of compile functions and transclusion, stumbling upon this Plnkr. Within this Plnkr, I discovered an 'advanced tab' directive. This discovery sparked my curiosity, leading me to experiment and create my own ...

Move the cursor and watch as the Hover Image seamlessly follows its path

Currently, I am attempting to create an interactive hover effect with an image that moves along with the mouse cursor. While I have come across various resources for achieving this effect, the limitation of working within a Wordpress theme restricts my ab ...

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...

Exploring characteristics using DocumentTraversal

My goal is to list out the attributes of elements using DocumentTraversal specifically for IE11. While I have been successful in enumerating element attributes, I am facing an issue when trying to do the same with attributes. The enumeration stops at the f ...

Importing and exporting JSON information into Cytoscape.js

After coming across this interesting question and answer, I decided to create this JSFiddle to explore further. My objective is to find an effective way to export and import JSON data into cytoscape.js. The approach I took involved using JSON.stringify(c ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

Submitting Form data to MySQL database with Node.js using Express framework

Currently, I'm working on a server.js file in Node that is intended to send form data from an HTML file to MySQL. However, I seem to be encountering a syntax error with my code. Below, you'll find the code snippet along with the specific error me ...

Managing an Infinite Amount of Inputs in React

I'm designing a React component that enables users to send emails to their friends and family. By default, the component includes 3 input fields, but users can easily add more by clicking a button. To implement this feature, I plan to create a button ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Backstretch malfunctioning

Looking to enhance my webpage with a backstretch image slideshow effect using the body background, but encountering issues. The code I have included before the </head> tag is: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery ...

One of the two identical pages is experiencing issues with the jQuery leanmodal while the other is

Despite having the same scripts and libraries loaded in two pages with identical templates, there is a slight difference in main content. Strangely, leanmodal only seems to work on the index page and not on any other page. <script type="text/javascrip ...

The ReactJS component is unable to resolve the specified domain name

Whenever I utilize a component like const React = require('react'); const dns = require('dns'); class DnsResolver extends React.Component { componentDidMount() { dns.resolve('https://www.google.com', (err, addres ...