An alternative approach to applying multiple filters in AngularJS without using chaining

I am currently facing an issue with using two filters in my ng-repeat. Here is how I have set it up:

<tr ng-repeat="c in datasets | filter:filterDataSet | filter:filterExpressionforPerspective | orderBy:'-id'" id="{{c.data_id}}" animate-on-change='c.program_name + c.organization + c.data_type_fmv_wami + c.perspective + c.status' ng-animate="'animate'">

Initially, when I only have the first filter 'filter:filterDataSet', all of the data displays correctly on the page. Here is how I am implementing 'filter:filterDataSet':

Filter: <span class="input-icon">
            <input placeholder="Filter dataset list..." class="nav-search-input" ng-model="filterDataSet" ng-change="resetLimit();" autocomplete="off" type="text" style="width:300px;" focus>
            <i class="search-icon fa fa-search nav-search-icon"></i>
          </span>

However, when I add the second filter 'filter:filterExperessionforPerspective', the data no longer appears on the page and only shows based on 'filter:filterExperessionforPerspective'. Below is a snippet of code for 'filter:filterExperessionforPerspective' where a dropdown is used:

Angular code:

$scope.filterExpressionforPerspective = function(dataset) {
        return (dataset.perspective === $scope.selectedPerspective.value);
    };

HTML dropdown:

<label for="PerspectiveDD">Perspective
              <select name="PerspectiveDD" ng-model="selectedPerspective" style="color:black;" ng-options="Perspective as Perspective.value for Perspective in perspectiveOptions">
                {{selectedPerspective.value}}
              </select>
            </label

I am trying to understand how to make both filters work as an 'OR' instead of chaining them as an 'AND'. Any assistance would be greatly appreciated! Thank you.

Answer №1

Learn how to personalize a filter

angular.module('app', [])
.filter('customizedFilter', function(){
   return function(dataList, preference1, preference2){
       return dataList.filter(function(item){
        (item.property === preference1)|| (item.view === preference2.choice) ;
       }
    }
});

Implement it in your html code

<tr ng-repeat="c in datasets | customizedFilter: filterDataSet:selectedView | orderBy:'-id'" id="{{c.data_id}}" animate-on-change='c.program_name + c.organization + c.data_type_fmv_wami + c.view + c.status' ng-animate=" 'animate'">

Answer №2

After trying out different approaches, I eventually implemented two distinct filters:

<tr ng-repeat="c in datasets | filter: miataDataFilter | filter: filterDataSet | orderBy:'-id'" id="{{c.data_id}}" animate-on-change='c.program_name + c.organization + c.data_type_fmv_wami + c.perspective + c.dataset_status' ng-animate=" 'animate'">

The filterDataSet function utilizes animate-on-change feature to filter the data set list based on user input:

<input placeholder="Filter data set list ..." class="nav-search-input" ng-model="filterDataSet" ng-change="resetLimit();"  autocomplete="off" type="text" style="width:300px;" focus>

Meanwhile, miataDataFilter is a customized filter within my datasetCtrl code:

//custom filter to search dataset by Perspective and/or Data Type
    $scope.miataDataFilter = function(dataset){
        //creating flags undefined and null selections
        var selectivePerspectiveIsDefined = typeof $scope.selectedPerspective != 'undefined' && $scope.selectedPerspective != null;
        var selectedDataTypeIsDefined = typeof $scope.selectedDataType != 'undefined' && $scope.selectedDataType != null;

        //Perspective is only selected
        if(selectivePerspectiveIsDefined && !selectedDataTypeIsDefined){
            return (dataset.perspective === $scope.selectedPerspective.value);
        }
        //Data Type is only selected 
        else if(!selectivePerspectiveIsDefined && selectedDataTypeIsDefined){
            return (dataset.data_type_fmv_wami === $scope.selectedDataType.value);
        }
        //Perspective and Data Type are both selected
        else if (selectivePerspectiveIsDefined && selectedDataTypeIsDefined)
        {
            return (dataset.perspective === $scope.selectedPerspective.value && dataset.data_type_fmv_wami === $scope.selectedDataType.value)
        }
        //Nothing is selected
        else
            return true;
    }

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 Vue mixin properties are devoid of content and lack reactivity

Could you please guide me in the right direction if this question has already been asked before? I really hope it's not a duplicate. I have a Vue application that is compiled using Webpack@NPM. In order to pass a property (roles) across all component ...

Relocating to new pages as WebSocket connection terminates and then reconnects

Currently working on a React project with Vite, encountering an issue where the websocket connection closes and re-establishes when navigating to another page using the sidebar. Main.tsx :- import ReactDOM from 'react-dom/client'; import App fro ...

The Vuex commit has exceeded the maximum calstack size limit

Currently facing an issue https://i.sstatic.net/l1WWH.png The error seems to be isolated to this specific section mounted() { this.$nextTick(() => { let ctx = this.$refs.canvas.getContext('2d') let { chartType, dataOptions ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...

jquery.event.drag - Execute code for each increment of X pixels dragged

Currently, I am utilizing jquery.event.drag.js for a project I am developing. My goal is to execute a script after every interval of X pixels dragged along the X axis. Below is a snippet of the code I have implemented. $('body').drag(function( e ...

Using conditions with lambda functions in Python

Is there a more efficient code solution available for this scenario? For example, in the list nums = [1, 2, 3, 4, 5, 6], if we want to perform a simple calculation using lambda on elements where num%2 == 0 like so: print map(lambda n:n**2, filter(lambda ...

Obtain the bounding box of an SVG element while it is not visible

I've been grappling with this issue for more than a day now, but I'm still unable to find a solution. My challenge lies in the need to scale an SVG image for responsive design purposes. Since I have to manipulate the SVG code on the client side, ...

Activating object functions through a click

Currently, I am in the midst of creating an interactive story using Jquery. One challenge I am facing is how to dynamically change the text every time a button is clicked to display the next dialogue function. To tackle this issue, I have structured an o ...

Steps for implementing target='_blank' on a <Link> tag with more than just an <a> element inside

I'm facing an issue where I need to open a new browser tab and redirect to a specific URL when a button is clicked. The problem arises when using an element other than an anchor tag inside the Next's <Link> element, as it seems to ignore th ...

Are there any ways to bring visual attention to a GoDaddy template's SEND button using HTML or JS when the original code is unavailable?

I'm currently working on a GoDaddy website using a template that doesn't clearly highlight the SEND button in a Contact Us form. In order to comply with WCAG accessibility standards, active elements must have visible focus indicators. However, si ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...

Effortlessly switching back and forth between OData and WebAPI in breezejs

I find myself in a bit of a complex situation. My application requires access to two different services: one is an ODATA service, and the other is a WebAPI (with Breeze controller) service. The architecture of my application revolves around AngularJS modu ...

Assorted Three.js particles

As a beginner in the world of three.js, I'm currently tackling the challenge of incorporating 1000 particles, each unique in size and color. The current roadblock I'm facing is that all particles end up the same color and size when using a Partic ...

What issues can be identified in this ajax.js script?

This particular function is designed to verify the existence or availability of a user login, yet even when the user database table is empty, the form consistently indicates that there is a duplicate entry. As a result, the submit button disappears. What c ...

Enhancing the mobile menu with a feature that allows users to easily close the

I am currently designing a mobile menu for a website that I created using Wordpress with the Divi Theme. When the user clicks on a "hamburger icon", it triggers a fullscreen menu to open: mobile menu If you tap on "Termine", it will reveal a submenu: mo ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...

Visualizing dynamic data with Ajax in a column bar chart

Trying to implement highcharts column bar charts, but facing issues with refreshing the data without reloading it. Unfortunately, I don't have access to the code I used at work to resolve this. Considering setting up a loop to run multiple times with ...