Searching by multiple parameters in Angular.js

I have a script that scans through a field and highlights the words related to the search input. I want this script to not only filter by title, but also by name. How can I adjust the code to filter both the title and name when searching?

<li ng-repeat="item in data | filter:search.title"
   ng-bind-html="item.title | highlight:search.title">
</li>

http://jsfiddle.net/sgo3wxwc/

Answer №1

If you need to filter by multiple options, simply gather them in an object like this:

<li ng-repeat="item in data | filter:{title:search.title,name:search.name}"
   ng-bind-html="item.title | highlight:search.title">
</li>

It is advisable to use filters in the controller to prevent triggering the $digest cycle unnecessarily.

Answer №2

<div ng-app="myApp" ng-controller="myCtrl">
      <input type="text" placeholder="Enter keyword to search" ng-model="search.title">
  <ul>
      <!-- filtered list -->
       <li ng-repeat="item in data | filter:{title:search.title,name:search.name}"
   ng-bind-html="item.title | highlight:search.title">
         {{item}}
      </li>
      </ul>
</div>

Below is the script code:

    var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.data = [
            { title: "Bad",name:'bill' },
            { title: "Good",name:'Goe' },
            { title: "Great",name:'Brad' },
            { title: "Cool",name:'yan' },
            { title: "Excellent",name:'mikle' },
            { title: "Awesome",name:'mosa' },
            { title: "Horrible",name:'morteza' },
          ]

}).filter('highlight', function($sce) {
    return function(text, phrase) {
      if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
        '<span class="highlighted">$1</span>')

      return $sce.trustAsHtml(text)
    }
  })

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

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

Text in d3.js vanishing while undergoing rotation

I have been struggling for hours with what seems like a simple problem and haven't made any progress. I'm hoping to receive some valuable advice from the brilliant minds on stackoverflow. You can view my demo at I attempted to use jsfiddle to s ...

Attempting to construct a dynamic table using Angular framework

I created a plunk showcasing a directive with a table. I'm attempting to dynamically add one row with two cells to the table, but only one cell is appearing. Can anyone spot what may be causing this issue in the code? Javascript angular.module(&apos ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

Need to get an item from a collection at the library?

Is it possible to import and use an object from a library? For instance, suppose we have a file named data.js with the following content: return { "name": "Testing" } In the file index.js, could we do something like this: const data = require('. ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...

Execute the gulp module on the source files

Recently, I've been delving into the world of gulp and trying to enhance the readability of my js source files. I have a task in place (which executes successfully) that utilizes 'gulp-beautify' to beautify the js files: gulp.task('js& ...

When I try to execute `npm start` on Ubuntu 16.04, I encounter npm errors

My Ubuntu 16.04 OS has node v7.10.1 and npm v4.2.0 installed. I encountered an error when trying to start npm or sudo start npm. Everything was working fine this morning, but now I'm getting errors. Can someone please help me troubleshoot this? npm E ...

Utilizing material-ui's LocalizationProvider to display times in a different time zone

My application requires material-ui date and time pickers to function based on a remote time zone specified by the server. I want the today circle on the date picker to accurately reflect today in the remote time zone, and I need to convert the datetimes i ...

Retrieve the URL for the React component

I'm facing some challenges with React fundamentals :/ I have a piece of code that creates a table using JSON data: import React from 'react' import { DataTable } from 'react-data-components'; function createTable(data) { ...

Access the filtered data with Vuex and Firestore to display the results

I am looking to enhance my project by implementing a filtering feature. I currently have a buttons component that will trigger the filter search. When I click the restaurant button, it should display the shops with a "Restaurant" value in Firestore. Conv ...

Contrast the Django variable against the Angular variable

I am encountering a challenge while working with Django backend and Angular frontend. The issue at hand is comparing a variable value from a Django view with another variable value from Angular. I have attempted the following simple approach, but it does ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

ES5 enables the extension of classes in React

This ES6 syntax works fine for me: import {Component} from 'react'; class A extends Component {} class B extends A { // I can redeclare some methods here } But how would one implement this using ES5? Like so: var React = require('reac ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

What could be causing this error to occur in my JavaScript React code?

ERROR - '}' expected. Parse error. I'm experiencing issues with this code snippet where I try to fetch data for a graph using React, but I keep getting the parse error mentioned above. vehiculoPorColores = () => { const _this = this fet ...

Incorporate an object property value into an established Angular/Node app by using the syntax " :12 " instead of just " 12 "

My current project is an Angular/Node MEAN stack application, but my primary concern revolves around JavaScript. When I receive a response object, it includes an SQL identity id console.log(response.recordset[0]); The output is "":12 I want to assign t ...