What are the steps to effectively utilize the $filter('filter') function when filtering multiple columns with OR as the condition?

In my AngularJs Application, I have a collection of customers.

var customers = [
    {
        "Name": "Alfreds Futterkiste",
        "City": "Berlin",
        "Country": "Germany"
    },
    {
        "Name": "Ana Trujillo Emparedados y helados",
        "City": "México D.F.",
        "Country": "Mexico"
    }
];

I am trying to filter these customers based on multiple columns. The code I used below did not yield the desired results.

$scope.customers = (
    $filter('filter')(customers, {
        Name: $scope.criteria.searchtext,
        City: $scope.criteria.searchtext
    })
);

UPDATE

Can someone guide me on converting the above syntax to use 'OR' logic? Please refer to this CodePen Sample for illustration.

Answer №1

When it comes to custom filtering in Angular, I find that utilizing Array.prototype.filter() is a simple and effective approach. Another option is to incorporate a function argument with $filter.

In the scenario below, we are assuming a partial match:

$scope.customers = customers.filter(item){
     var term = $scope.criteria.searchtext.toLowerCase();
     //partial match 
     return item.Name.toLowerCase().indexOf(term) >-1 
            || item.City.toLowerCase().indexOf(term) >-1;
});

Furthermore, this code snippet can easily be transformed into an Angular custom filter for use within the view.

Answer №2

Implement a filter for customers

<tr class="animate" ng-repeat="customer in customers | filter: criteria.searchtext">
<td ng-bind="customer.Name"></td>
<td ng-bind="customer.City"></td>
<td ng-bind="customer.Country"></td>
</tr>

Assign the customers to the $scope as shown below

$scope.customers = [{}]; // Array containing customer data

View the completed Solution

Please provide feedback on whether this solution meets your needs.

Answer №3

I developed a unique Custom filter that can effectively filter multiple columns using the OR condition. Take a look:

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

function MyCtrl($scope,myFilterFilter) {
 $scope.criteria = {};
  $scope.criteria.searchtext = 'Berlin';
var customers =[{"Name":"Alfreds Futterkiste","City":"Berlin","Country":"Germany"},
{"Name":"Ana Trujillo Emparedados y helados","City":"México D.F.","Country":"Mexico"},{"Name":"Futterkiste","City":"Berlin","Country":"Germany asfdasdas"}]
$scope.customers=myFilterFilter(customers,$scope.criteria.searchtext,$scope.criteria.searchtext);
 
}


angular.module('myApp').filter('myFilter', function() {
  return function(customers,name,city) {
      var yes = [];
      angular.forEach(customers, function(value, key) {
        if ((value['Name'] === name) || (value['City'] === city)) {
           yes.push(value);              
        }
        
    });
    console.log(yes)
    return yes
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<div ng-controller="MyCtrl" ng-app="myApp">
  Hello, {{customers}}!
</div>

Check out the fiddle here

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

What is the reason for the restriction on referencing DOM nodes in Angular expressions?

The guidelines provided in the angularJs documentation state that attempting to reference a DOM element within an angular expression is considered erroneous. What is the reasoning behind this restriction? What risks or issues is AngularJS aiming to mitig ...

Capable of generating accounts using Postman, experiencing difficulties with creating accounts from React

Currently, I am working on a project that utilizes a React/Spring Boot/MYSQL stack and I have encountered an error message stating "POST 415: SyntaxError: Unexpected end of input at line 67". Line 67 is as follows: }).then(res => res.json()) This sect ...

Error message indicating an issue with ng-repeat when working with an

$http.get('***').success(function(data, status,response) { $scope.items=data; var getdata=JSON.stringify(data.D_Services); console.log(getdata); }); im retrieving in the console D_Services: "Wash,Tyres,Spares,Accessories"; Could someone please ...

Vue should only activate the element that has been clicked on

I'm currently working on my first Vue project and encountering an issue with triggering a child component within a table cell. Whenever I double click a cell, the `updated` event is being triggered in all child components associated with the table cel ...

No files found in dist/ directory when using Vue.js

Beginner's Note I must confess that I am a novice when it comes to web development. Please bear with me if this question seems silly; I appreciate your assistance in advance. Initial Setup My current node version is 16.15.1 and npm version is 9.5.0 ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

Having numerous sections condensed into one cohesive page

Currently, I am working with backbone.js to develop a single-page application that takes inspiration from the functionality of trello.com. I am interested in learning how to display multiple pages on top of the original page and effectively structure the ...

A guide on utilizing Stripe's payment_intent_data feature to automatically send an email to the customer following a successful transaction

I am struggling to send an email to the client after a successful payment. The documentation mentions setting "payment_intent_data.receipt_email", but my code below is not working as expected (no emails are being received). How should I properly configur ...

Check if the data-indices of several div elements are in sequential order using a jQuery function

Is there a way to implement a function in jQuery-ui that checks the order of div elements with data-index when a submit button is pressed? I have set up a sortable feature using jQuery-ui, allowing users to rearrange the order of the divs. Here is an exam ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

Establish a secure connection to MySQL through SSH tunneling with node-mysql

Is it feasible to establish a connection to the MySQL server using an SSH key instead of a password when utilizing the node-mysql npm package? ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

Utilize Vue.js to incorporate an external JavaScript file into your project

Currently, I am utilizing Vue.js 2.0 and facing an issue with referencing an external JavaScript file in my project. The index.html file contains the following script: <script type='text/javascript' src='https://d1bxh8uas1mnw7.cloudfro ...

Is it possible that .focus() does not function on a duplicated object?

Greetings to all! I have created a form with rows of input text fields. Users can add as many rows as needed by clicking the 'add row' button. The functionality to clone() for adding rows is working perfectly. In each row, an input field can o ...

An intriguing inquiry regarding HTML form intricacies

Looking to enhance the source code by adding a new column to display Client Mobile, Client Office Telephone, and Client E-mail in a separate popup PHP page. My attempt involved adding a form and submit button to generate the new column. However, pressing ...

What is the best way to limit dates on an angular-datepicker?

I'm having trouble setting the maximum and minimum date in angular-datepicker. For more information, you can visit the angular-datepicker link. <div date-picker="start" min-date="Date string | Expression" max- date="Date string | Expression">&l ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

Having trouble getting Next.js 404 page to function properly with the .tsx extension?

My latest project involved creating a Next.js application using regular JavaScript, which led to the development of my 404 page. 404.js import { useEffect } from "react"; import { useRouter } from "next/router"; import Link from " ...