Discovering the applied column filter in Angular's UI-Grid

I am currently working with ui-grid and implementing server-side filtering. I make a request to the API for each column based on the filter value, with the default parameter being empty.

     var filterOptions = {
                filterBy: '&$filter=',
                filterParam: ""
            };

  // The API call is structured like this

?$orderby=id-&pageSize=250&pageNbr=1&$filter=

If any filter is applied, the next request will be sent like this

param:     filterOptions.filterParam = 'eventTypeId==' + evtTypeId

request:   ?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2

My objective is simple - I want to detect if a filter is already in place and send a request similar to this

?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2,studyId==1

Unfortunately, I am unable to identify any applied filters. Any assistance would be greatly appreciated.

Below is my code snippet:

Column Definitions

 $scope.gridOptions.columnDefs = [
                {
                    field: 'title',
                    cellClass: getCellClass,
                    useExternalFiltering: true
                }, {
                    field: 'description',
                    cellClass: getCellClass,
                    enableFiltering: true,
                    useExternalFiltering: true
                },
                // Additional column definitions...
            ];

RegisterApi

 $scope.gridOptions.onRegisterApi = function (gridApi) {

                // Defined behaviors for grid interactions
                
             };

Where getData() Function Definition

var getData = function () {

                // Functionality of fetching data from the API and updating the grid view

            };

Link to my Plunker demo (API details cannot be provided)

Answer №1

Here is the functioning code:

  gridApi.core.on.filterChanged( $scope, function() {

                // Initializing variables
                var grid = this.grid;
                var columns = grid.columns;
                $scope.columnTitle = grid.columns[1].filters[0].term;
                $scope.columnDesc = grid.columns[2].filters[0].term;
                var columnType = grid.columns[3].filters[0].term;
                var columnStudy = grid.columns[4].filters[0].term;
                var columnPriority = grid.columns[5].filters[0].term;
                var columnSeverity = grid.columns[6].filters[0].term;
                var columnStatus = grid.columns[7].filters[0].term;
                var columnCreatedDate = grid.columns[8].filters[0].term;
                var columnModifiedDate = grid.columns[9].filters[0].term;

                // Creating request for selectable filters
                var query = [];
                var string;
                function generateRequest (id, param) {

                    if(param === "title==" || param === "description=="){
                        query.push(param + "*" + id + "*")
                    } else {
                        query.push(param + id);
                    }

                    if (query.length <= 1){
                        return query
                    } else {
                        string = query.join(";");
                        return string;
                    }
                }

                // Defining behavior for canceling filtering
                $scope.isfilterclear = true;

                angular.forEach(columns, function( col ) {
                    if(col.filters[0].term){
                        $scope.isfilterclear = false;
                    }
                });
                if($scope.isfilterclear) {
                    $timeout(function() {
                        $rootScope.refresh()
                    },500);
                }

                // Filtering behavior for columns
                if($scope.columnTitle) {
                    $scope.$watch('columnTitle', function (newVal, oldVal) {
                        filterOptions.filterParam =  generateRequest(newVal, 'title==*');
                    }, true);
                    getData()
                }
                if($scope.columnDesc) {
                    $scope.$watch('columnDesc', function (newVal, oldVal) {
                        filterOptions.filterParam =  generateRequest(newVal, 'description==');
                    }, true);
                    getData()
                }
                if(columnType) {
                    filterOptions.filterParam = generateRequest(columnType, 'eventTypeId==');
                    getData();
                }
                if(columnStudy) {
                    filterOptions.filterParam = generateRequest(columnStudy, 'studyId==');
                    getData();
                }
                if(columnPriority) {
                    filterOptions.filterParam = generateRequest(columnPriority, 'priorityId==');
                    getData();
                }
                if(columnSeverity) {
                    filterOptions.filterParam = generateRequest(columnSeverity, 'severityId==');
                    getData();
                }
                if(columnStatus) {
                    filterOptions.filterParam = generateRequest(columnStatus, 'statusId==');
                    getData();
                }
                if(columnCreatedDate){
                    filterOptions.filterParam = generateRequest($rootScope.setFilterDate, 'occuredDate>=');
                    getData()
                }
                if(columnModifiedDate){
                    filterOptions.filterParam = generateRequest($rootScope.setFilterDate, 'occuredDate>=');
                    getData()
                }
            });

In this section of code, I have defined a custom function with two parameters where I am passing my request parameter for each call. I am still evaluating the elegance of this method but after two weeks of testing, this was the best solution I could find.

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

Trouble arises when attempting to open a popup programmatically using jQueryMobile due to a JavaScript error

When attempting to open a jQuery Mobile popup programmatically, I encountered a JavaScript runtime error. The specific error message is: 0x800a138f - JavaScript runtime error: Unable to get property 'nodeName' of undefined or null reference I c ...

Updating input from a dynamic select element can be done by listening for changes on

Currently, I am utilizing a ng-repeat connected to a collection called vm.stations. Whenever a button is clicked, it inserts an item into the collection. User Interface <div class="row" data-ng-repeat="station in vm.stations"> <select ng-opt ...

In PHP, validating a value stored in a database against one entered in a text box

My form consists of multiple text fields, with the number determined by the amount of data in a database. Both inputs are integers. I would like to set up a validation where an error is triggered if the inputted value exceeds the corresponding value in t ...

What could be the reason for the absence of {{ list.title }} on display

I'm currently learning how to develop my first MEAN stack app by following a tutorial on YouTube. However, I've encountered an issue where the title of the list is not displaying correctly. I'm using Insomnia to create the lists. Here's ...

Something seems to be preventing Div from appearing and there are no error messages appearing

I've been attempting to create a menu, but the toggle div for the menu isn't visible Following a tutorial where an individual sets up a menu, there is a div with a menu icon in the top left corner. Despite meticulously copying the code from the ...

Res.redirect is failing to redirect and displaying error message 'Connection Unavailable'

Currently, I am in the process of developing a NodeJS + ExpressJS Ecommerce Website. My focus is on enhancing the functionality of the admin panel feature. Users can navigate to /admin/products/new to access a form. When the user completes and submits this ...

Adjusting the Image Width in React to Match Bootstrap Column Width

Exploring the capabilities of the react-image-mapper library, I stumbled upon an interesting feature: the ImageMapper component offers a prop called width, representing the image width in pixels. Integrating this component into my application based on the ...

Using Vue components or elements within the v-html directive allows for dynamic rendering

One of the challenges I'm facing involves handling data from a blog post, specifically the user-submitted text stored in post.text. Similar to Twitter, users can mention other users using syntax like I am tagging @user1 in this post. My goal is to aut ...

Unable to modify the innerHTML of an SVG element in Internet Explorer

I am facing an issue where I cannot modify the SVG code using JavaScript in Internet Explorer. When I inspect the element on IE and select the svg, it only displays: <svg xmlns="http://www.w3.org/2000/svg" role="img" style="stroke-width: 0px;" viewBox ...

Animating color on a JSON model when loaded in three.js

Can you animate the colors of a loaded JSON model in three.js? In my code, I used the ObjectLoader() to render the model. Now, I want to be able to animate the color of the model after it's been loaded. var objectLoader = new THREE.ObjectLoa ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

Pixel information from previous canvas remains intact post resizing

I have crafted a canvas and loaded pixel data at specific locations using the following code snippet. let maskCanvas = document.createElement("canvas"); let patchWidth = 30; let patchHeight = 30; let scale = 3; maskCanvas.setAttribute("class", "mask"); ...

Running JavaScript code along with HTML elements extracted from a jQuery ajax callback

Alternatively, not exactly "executing," but rather updating a pre-existing function with a function returned in the response. Step 1 I have an HTML5 page detailing a specific location. The server-side includes a ColdFusion file called "MapFunction.cfm" ...

Invoking function through click event binding

Check out this fiddle I have: http://jsfiddle.net/jj258ykp/2/ On BTN2 and BTN3, I get an alert when I click, but not on BTN1. I want to see the alert on BTN1 as well. Take a look at the coffeescript code snippet below: class A method: -> ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

Is it true that Javascript's onclick global event handlers fire prior to the page being fully loaded

I'm trying to set a global event handler for an image, but running into issues. When I use the code document.getElementById("post_image").onclick = photoEnlarge;, it returns an error saying Uncaught TypeError: Cannot set property 'onclick' ...

Why does a void function get passed as a plain object in TypeScript?

Why does a void function pass as a plain object? Is this intentional or a mistake in the system? playground type PlainObject = { [key: string]: any }; const foo = (value: PlainObject) => { } const voidFn: () => void = () => { }; // Error as ex ...

React: Error parsing - Missing closing JSX tag for <input> element

I am currently learning React and am in the process of working on a new component. Here is the code snippet that I have so far: order-item.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...