"Implementing a filter with multiple select options in AngularJS

As a beginner delving into Angular, I find myself working with a multiple select feature to filter a list by name.

<select multiple ng-options="data.name for data in datas" ng-model="filterData">
</select>

Currently, I am able to filter with only one value using the following:

<div class="container " data-ng-repeat="data in datas | filter : filterData[0].name">

However, my goal is to pass an array to the filter so I can filter by multiple values simultaneously.

Is creating my own custom filter the way to achieve this?

{
         "datas": [
            {"name": "first", "id": 1},
            {"name": "two", "id": 2},
            {"name": "three", "id": 3},
        ]
}

Thank you!

Answer №1

If you want to create a personalized filter and set specific filter values in advance, follow these steps:

<div class="row " ng-repeat="item in items | customFilter : withKeywords">

var _filterTheseTerms = ["apple", "banana", "orange"];
$scope.withKeywords = function(element) {
    return _filterTheseTerms.some(term) {
        return element.name.includes(term);
    });
}

Answer №2

  Creating a new AngularJS module called 'myApp':

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

  Defining a controller named 'myController' and passing the function to it:

myApp.controller('myController', myController);

  Implementing the myController function that populates data in arrays:

function myController($scope) {
    $scope.datas = [{
      "name": "first",
      "id": 1
    }, {
      "name": "two",
      "id": 2
    }, {
      "name": "three",
      "id": 3
    }, ];

    $scope.filterData = [];

    Setting up a filtering function byArray using item names:

    $scope.byArray = function(myArray) {
      return function(item) {
        return !myArray.some(function(word) {
          return item.name.indexOf(word.name) > -1;             
        });
      };

    }
  }
<div ng-app="myApp" ng-controller="myController">
  <select multiple ng-multible="true" size="3" ng-options="data.name for data in datas" ng-model="filterData">
  </select>
  <div class="container" data-ng-repeat="data in datas | filter : byArray(filterData)">{{data.name}}
  </div>
</div>
<script src="https://code.angularjs.org/1.3.11/angular.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

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{ ...

Forwarding AngularJS events using socket.io with the use of deferred promises

I recently started using the Angular library angular-socket-io for my project. However, I encountered a challenge where I needed to implement authentication within the app before initializing the socket.io interface. To address this issue, I found and impl ...

Breaking down a JSON Object in Angular 4: Step-by-step Guide

I am working on integrating a JSON API with an Angular 4 frontend, and my goal is to display the data from this JSON Object. Here is the code I have used: <div *ngFor="let Questionnaire of struc.data"> <span>{{Questionnaire.attributes.con ...

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...

Encapsulate all ASP.NET JSON responses by returning an anonymous object

Exploring ASP.net (Visual Studio 2010, .NET 3.5) for the first time and hoping to achieve the following: Using OperationContracts to serve webservice data in JSON format. A mobile app built with angularJS is consuming these JSON responses. The goal is to ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Ways to show an input box even when there are no results found

I currently have a database with 5 books, but only 3 of them have prices listed. How can I modify my code to display an input box for all books, regardless of whether they have a price in the database? I am new to coding, so I would appreciate it if you co ...

Using pre-existing code but with personalized modifications

I have several pages containing code for a footer area with buttons and other elements at the bottom: <nav class="navbar navbar-default navbar-fixed-bottom" role="navigation"> <div class="container"> <div class="navbar-inner"> ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Storing information in a loop using AngularJS's ng-repeat functionality

I have a language table, a table with custom tablenames, and a table with translations. My goal is to insert a new table in all languages. In my Controller, I am calculating the number of elements in my language table and then generating the view: var co ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

What are some effective ways to address conflicts between select2 versions 3.5 and 4.0?

Although not identical, the issue outlined in this discussion thread - https://wordpress.org/support/topic/select2-conflicting-with-acf-v5 resonates with my current predicament. In the scenario of a WordPress website with two plugins, one employing select ...

Is it secure to transmit Tenant ID's as GET parameters to the API in a Multi-Tenant database environment?

When working with a Multi-Tenant database, is it secure to pass Tenant ID's as query string parameters to the API while using popular JavaScript-based UI platforms like Angular or Vue and ensuring both the site and the API are HTTPS? For example, let ...

passport.js and express: TypeError - Router.use() must be given a middleware function, but instead received a ' + gettype(fn)

I encountered an error while using passport.js with Express.js TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) This issue arose from the following code: passport/local.js var LocalStrategy = require("passport ...

Having difficulties retrieving the value of the div in the voting system

Whenever the element with the id #upvote is clicked, the value of the element with the id #vote increases by 1. On the other hand, when the element with the id #downvote is clicked, the value decreases by 1. However, there seems to be an issue where if the ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this: var users = [ { first: 'Jon', last: 'Snow', email: '<a href="/cdn-cgi/l/email-protection" class="__ ...

No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console. Below is the data: mydata = { "id": "661", "name": "some name", "description": "some desc", ...

The sole focus is on the animation within the div

Is it possible to have a circle animation within a button without overlapping it? Check out my code on this fiddle. $(document).ready(function(){ $('button').on("mouseup",function(){ $('#mousemark').removeClass("c ...