AngularJS - Filter for selecting multiple options

Currently, I am utilizing $filter to perform filtering on my array.

var filteredData = params.filter() ?
    $filter('filter')($scope.myNgTable.data, params.filter()):
    $scope.myNgTable.data;

I have implemented a multiple select filter for filtering, however, it returns an array: col: ["a","b"], which seems incompatible with $filter according to my observation.

What I desire is that when the filter is col: ["a","b"], it should display all rows where col contains "a" or col contains "b". (Alternatively, if there's only a way for equal comparison, such as: col == "a" or col == "b")

Can this be achieved?

Response:

.filter("in_Array", function ($filter){
    return function(data, filter){
        var out = [];
        $.each(filter, function(key,val) {
            var obj = {};
            for(var i=0;i<val.length;i++) {
                obj[key] = val[i];
                var tmp = $filter('filter')(data, obj);
                out = $.unique($.merge(out, tmp));
            }
        });
        return out;
    };
});

Answer №1

Take a look at this example demonstrating the use of multi-filter when clicking on a checkbox:

http://jsfiddle.net/rzgWr/123/

HTML:

 <div ng-controller="MyCtrl">
        <h4>Choose a brand to view the models</h4>
        <div ng-init="group = (cars | groupBy:'make')" style="width:100%">
            <div ng-repeat="m in group"   style="width:100px; float:left;">
                <b><input type="checkbox" ng-model="useMakes[$index]"/>{{m}}</b>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div>
            <ul>
                <li  ng-repeat="car in cars | filter:filterMakes()"><p><b>{{car.make}} - {{car.model}}</b></p></li>
            </ul>    
        </div>
    </div>

JS:

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

function MyCtrl($scope, filterFilter) {
    $scope.useMakes = [];

    $scope.filterMakes = function () {
        return function (p) {
            for (var i in $scope.useMakes) {
                if (p.make == $scope.group[i] && $scope.useMakes[i]) {
                    return true;
                }
            }
        };
    };

    $scope.cars = [
        {model: '316', make: 'Bmw'},
        {model: '520', make: 'Bmw'},
        {model: 'Fiesta', make: 'Ford'},
        {model: 'Focus', make: 'Ford'},
        {model: 'Clio', make: 'Renault'},
        {model: 'Toledo', make: 'Seat'},
        {model: 'Leon', make: 'Seat'},
        {model: 'Insignia', make: 'Opel'},
        {model: 'Astra', make: 'Opel'},
        {model: 'Corsa', make: 'Opel'}
    ];    
}


var uniqueItems = function (data, key) {
    var result = new Array();
    for (var i = 0; i < data.length; i++) {
        var value = data[i][key];

        if (result.indexOf(value) == -1) {
            result.push(value);
        }

    }
    return result;
};

myApp.filter('groupBy',
function () {
    return function (collection, key) {
        if (collection === null) return;
        return uniqueItems(collection, key);
    };
});

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

Angular Azure Maps Animation Issue: Troubleshooting Guide

Utilizing Angular UI to showcase Azure map. I need to show real-time moving points on the azure map, similar to this Sample animation. I attempted using the 'azure-maps-control' module for point animation, but unfortunately, it didn't work ...

How to implement a file upload using AJAX in a Grails application within a g:

I am currently facing a challenge with uploading files via Ajax in a modal window form. I have tried various Grails plugins for ajax file upload but without success. Is there a way to achieve file upload without page refresh using the following code: &l ...

Issue with the status of a vue data object within a component

While working on updating my original Vue project, I encountered an error with the data object sports_feeds_boxscores_*. The website features three tabs that display scores for the major sports leagues. I am currently in the process of adding player stats ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

What could be the reason for the malfunction of .text() and .html() in cheerio js when used with node-fetch?

I am a beginner with Node JS and I am experimenting with the node-fetch and cheerio packages. My goal is to extract data from various websites by testing different URLs and selectors. However, in the code snippet below, regardless of the input selector or ...

Methods for hiding and showing elements within an ngFor iteration?

I am working on an ngFor loop to display content in a single line, with the option to expand the card when clicked. The goal is to only show the first three items initially and hide the rest until the "show more" button is clicked. let fruits = [apple, o ...

What is the best way to update a stylesheet dynamically within an Angular project?

I have been attempting to modify my bootstrap.css file in order to change the theme of my application: $scope.changeStyle = function (style) { $scope.myStyle = style + '/bootstrap.min.css'; $scope.$apply(); } The 'myStyle' ele ...

Identifying Internet Explorer's tracking protection through feature detection in JavaScript

It seems that Soundcloud does not offer support for browsers older than IE11, possibly due to tracking protection in IE9 and IE10. Is there a simple method using javascript to detect if tracking protection is enabled? I want to filter out all users with ...

Assign a variable value to populate several `<input>' fields

Using a variable named multiplier, I have successfully set the value of multiple input fields. Each input now has a custom attribute called my_value that is calculated based on three drop-down menus and a target table with corresponding values. The calcula ...

Identifying and troubleshooting issues in a React application operating within an nginx proxy

My React app is currently running on localhost:3000, while my Backend API is running on localhost:8181. To address cross-origin request issues and ensure compatibility, I have implemented an nginx reverse proxy setup for both the react app and backend API. ...

Creating a PDF document using an AJAX request

There is a button (link to controller/action) that, when clicked, triggers an action in PHP to validate and generate a PDF. This action checks if the PDF should be generated for the user, and if there are any errors, it will not generate the certificate bu ...

What is the best way to implement automation for this task using Selenium WebDriver?

As a newcomer to Selenium Webdriver (Js), I am eager to learn the basics but have hit a roadblock with a specific example: My current challenge is automating a Google search for "Diablo 2 Resurrected days until release" and then displaying the remaining d ...

Attempting to retrieve the MongoDB data for the designated field (data.site.alerts.alert) and transfer it to the client side

*****My code ***** import logo from './logo.svg'; import './App.css'; import React, { Component } from 'react'; import axios from 'axios'; export default class App extends Component { state = { arraydata: ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

Issues encountered with BootstrapTable AngularJS extension when data is asynchronously loaded

Utilizing the BootstrapTable AngularJS extension found here A demonstration on using this extension can be seen in this plnkr. However, the example provided involves static data generated prior to rendering the table. My goal is to get it working with dyn ...

What could be causing ReactJS to appear twice in this function's output?

Here is the information: { "location": { "name": "name1", "address": "addres1", "phone": "637636***", "facility": "facility1", ...

What is the best way to extract the .text(data) value and use it within a conditional statement?

My goal here is to create a function that disables a button if a username exists, and enables it if the username is available. I'm not very experienced with JavaScript/jQuery, so I could use some help. Any assistance would be greatly appreciated: $(& ...

Leveraging the power of Angular's latest router alongside the modern syntax

Currently, I am experimenting with the NG6-starter package to enhance my knowledge of Angular 1.5 component development using ES6. The routing in this package is handled by stateProvider, however, I am eager to transition to using angular-new-router for ro ...