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

The conditional expression in AngularJS is failing to execute

Having trouble with my login page that uses AngularJS to evaluate the username and password. Even when I input correct values, the conditional statement in the controller seems to return false. Below is a snippet of my HTML file: <div class="row"> ...

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

Puzzled on how to include a string in the parameter for a GET request?

Following the initial instruction to make a get request for a turtles route and send a JS object of turtles with their colors, I successfully implemented it like this: app.get('/turtles', function(req, res) { data = { Raphael: "Red", Le ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

ng-html-bind for a label with a checkbox

Currently, I have a view that uses the standard bootstrap layout for checkboxes. In this layout, the input is located within the label tag. <div class="checkbox"> <label ng-bind-html="vm.trustedHtml"> <input type="checkbox" ng- ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Find the object in an array that has the most recent date property

Suppose I have an array of objects like this : let sampleArray = [ { "id": 5, "date": "2016-01-15T16:18:44.258843Z", "status": "NEW", "created_at": "2016-01-29T13:30:39.315000Z", "updated_at": "2016-01-29T13:30:39.315000Z", "requ ...

Is there a way to limit the rotation of an a-camera in aframe?

One scenario could be enabling rotation around the z-axis within a range of -70 to 70 degrees, or alternatively, preventing rotation around any arbitrary axis. Thank you! ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

What is the process for issuing https requests with SuperAgent?

In my React Native Android project, I am utilizing SuperAgent, which works similarly to Node.js. My goal is to make an API call using the https protocol. However, when I simply use the following code: Req = SuperAgent .get(‘https://url...') ...

Unit Testing Angular controllers with an external variable in Jasmine framework

Looking for ways to create a unit test for a controller that utilizes a $scope.action variable that is defined outside the controller. controller( "MyController", [ "$scope", "$window", "httpInterceptor", function($scope, Service1, Service2, $wind ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

Annotation for inserting code inline

I'm new to angularjs and struggling to understand the explanation in the angular documentation about the role of the $scope as an array. Can someone explain what inline injection annotation means in this code snippet? var myApp = angular.module(&apos ...

leveraging the default browser behavior for the href and target attributes within an <a> element in Angular 2

How can the behavior of a simple anchor tag in Angular 2 be implemented without being overridden by the routing module? <a href="some url" target="_whatever"> It is crucial to prevent the routing module from highjacking the URL using the base href. ...

Validating Angular forms outside the <form> element

I have a rather unusual question - is it possible to retrieve the form status from outside the block? For example: <form name="form"> <input type="text" name="name" required /> </form> <button ng-disabled="form.$invalid"></b ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...