Customize the AngularJS ng-grid filter to format the filter text

Currently, I am working with ng-grid in AngularJS (v2.0.8) and I am interested in exploring the syntax for the filterText field within the API.

Specifically, I am looking to understand how to filter data based on certain columns and how to filter multiple entries within a column.

Despite the presence of numerous stack overflow questions related to ng-grid and filtering, I have not been able to find a comprehensive summary of the filterText format.

Answer №1

As of the moment writing this, comprehensive documentation on constructing the 'filterText' string is still lacking. Through analyzing the ng-grid.js code and making educated guesses, it becomes apparent that 'filterText' holds more power and versatility than what the current documentation implies.

Setting Up an Example

Before delving into the details, let's look at an example setup for a grid within a controller:

  $scope.pricing_data = data['records'];

  $scope.gridOptions = { 
    data: 'pricing_data',
    columnDefs: [
      { field: 'ticker', displayName: 'Ticker' },
      { field: 'date',   displayName: 'Date'   },
      { field: 'close',  displayName: 'Close'  },
      { field: 'volume', displayName: 'Volume' }
    ],
    filterOptions: {filterText: '', useExternalFilter: false},
    showFilter: true
  };

The 'pricing_data' object can contain JSON data fetched from the backend. A representation of the table might look similar to this:

Initially, the filterText is empty, displaying all records. The filter option allows users to refine what is displayed based on their search criteria.

The filter dropdown can be used to manipulate the 'filterText' variable, or filter criteria can be directly set in the controller code.

Searching Across the Grid

By default, filterText performs a regex search on every cell within the grid. For instance, searching for the character 'a' will display all entries containing 'a' in any cell. This behavior may suffice for some situations, but in cases with a large dataset, filtering by columns is usually more efficient due to the data structure and performance reasons.

Searching by Specific Columns

To search for a specific string or regex within a single column, the filterText format is:

filterText = '<displayName>:<value>'

For example,

In this case, searching for 'Date' followed by a colon ':' and then a partial string will only select records associated with a specific date. This method allows for precise filtering within a designated column.

To expand the search to include multiple options, the syntax is:

filterText = '<displayName>:<value 1>|<value 2>|...'

Each partial value is separated by a pipe '|', enabling multiple search criteria to be specified. This method allows for a more complex search scope.

Searching Across Multiple Columns

Extending the search to include multiple columns involves adding further syntax to the filterText format:

filterText = '<displayName 1>:<val 1>[|<val 2>|..];<displayName 2>:<val a>[|<val b>|..][;..]'

The use of semicolons ';' separates each column's search criteria. This method allows for cross-column searching with specific conditions.

Continuing with the example, a search for specific entries across different columns can be achieved by combining the search terms effectively.

Updates and Known Issues

Updates or edits in the data are seamlessly filtered through the grid, maintaining the search criteria set by the 'filterText'. This ensures that the filter remains persistent even after data updates.

Adressing Known Bug

An issue related to clearing the filterText causing browser performance concerns has been recently addressed. Referring to the ng-grid issues 777 and 848, updates have been made to alleviate this problem, enhancing the overall user experience.

UPDATE

Following the installation of ng-grid 2.0.8, the problem with clearing filters seems to have been resolved, indicating improved functionality.


Future Developments - ng-grid 3.0

Looking ahead, the development of ng-grid 3.0 is underway, aiming to build upon the existing features and possibly enhance performance and capabilities of the filter functionality. Continual improvements are essential to provide users with a robust and efficient data filtering experience.

Answer №2

After taking inspiration from JayInNyc's response, I made some adjustments to enhance user experience by simplifying the syntax. I focused on monitoring specific fields for filtering purposes, such as an input field for the name and city.

$scope.filterOptions = {
    filterText: ''
};
$scope.filterName = '';
$scope.filterCity = '';

$scope.$watch('filterName', function (value) {

    updateFilterText();
});

$scope.$watch('filterCity', function (value) {

    updateFilterText();
});

function updateFilterText()
{
    $scope.filterOptions.filterText = 'Name: ' + $scope.filterName + ';City:' + $scope.filterCity;
}

By the way, I initially attempted to incorporate the compile function, but encountered some difficulty in making it function properly. I tried the following approach which unfortunately did not yield the desired outcome.

filterOptions.filterText = $compile('Name:{{filterName}};Category:{{filterCategory}}')(scope);

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

Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below: var app = angular.module('myApp', ['ngRoute']); app.service('UserService', function() { this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""}; this.ad ...

The error message states: "change is not defined"

I am encountering an issue where I have 4 input boxes triggering a function on keyup using the onkeyup event. Strangely, I keep receiving an error stating that "change" (the function's name) is not defined. Despite correctly defining the function, I c ...

What is the best way to set up an external site iframe that utilizes PHP as a proxy on my web server without encountering CORS issues?

I came across a tutorial on using curl in php, and here is what I have implemented so far: index.html: <!DOCTYPE html> <html> <head> </head> <body> <iframe src="fetch.php" width="800" height="500"></iframe> </ ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

Using AngularJS and ChartJS together for stellar data visualization

I need help displaying the canvas element within custom angular directives. Being new to AngularJS, I am in search of a demo or idea regarding Chart.js integration with AngularJS. Important: I specifically require a custom directive for chart display. T ...

Coat the div with a uniform shade of pure white

I need assistance on applying a solid white background color to hide the text behind it. For better understanding, I have attached a screenshot as a reference. https://i.stack.imgur.com/f8Qd9.png The issue arises when I click on the dropdown in the heade ...

Using html data attributes to encode JSON data with strings

Looking for a way to pass data to JavaScript, I decided to create a template tag as shown below: from django.utils.safestring import mark_safe from django import template import json register = template.Library() @register.simple_tag def mydata(): r ...

Ensure that everything within the Container is not see-through

Fiddle:https://jsfiddle.net/jzhang172/b09pbs4v/ I am attempting to create a unique scrolling effect where any content within the bordered container becomes fully opaque (opacity: 1) as the user scrolls. It would be great if there could also be a smooth tr ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Is utilizing AngularJs for a Single Page Application (SPA) in a DDD project a wise decision?

Embarking on a new journey to implement an enterprise app following DDD principles. As my team and I delve into this world, we have much to learn and understand (please forgive any novice questions). The focus will be on creating a highly customized CMS. ...

Struggling with a peer requirement for grunt@~0.4.0 during the installation of grunt plugins? Here's how to resolve

I recently tried to set up some Grunt plugins such as grunt-contrib-clean and grunt-contrib-watch using the commands npm install grunt-contrib-clean --save-dev and npm install grunt-contrib-watch --save-dev However, I encountered the following warnings: n ...

Adjusting the X-Axis Labels on a Scatterplot using Chart.js 2

I'm working with Chart.js 2 to create a scatter plot using Epoch timestamps for the x coordinates and integers for the y coordinates. Is there a way to customize the x-axis labels on the graph to show dates in a more readable format? Update: I am cur ...

How can the datetime value of the Apex Charts datapoint be shown in the tooltip?

I'm struggling to find the proper location within the w.globals object to display the x-axis value, which is a datetime, in the tooltip of the datapoint. var chartOptions = { ... xaxis: { type: "datetime" }, tooltip: { x: { format: " ...

Jquery scripts seem to have a hit-or-miss success rate

Recently, I added a couple of Jquery scripts in my header to handle the fading in of a specific CSS class and scrolling down another one. Both of these classes are initially set to display: none in CSS, with Jquery responsible for making them visible. Here ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

A widget for Windows 7 that can handle both HTTP GET and POST requests

I'm currently working on a small gadget for our intranet and have set up a PHP file on our server for initial testing purposes. Everything seems to be functioning properly when I use the GET request method, but I would prefer to utilize POST in order ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

The jQuery .load() function does not seem to be functioning properly on secure HTTPS connections

After implementing an SSL certificate through Cloudflare on my website, I encountered an issue where a specific function returned an error code 0 and failed to load the URL content. How can I resolve this issue? $(function () { EnderReact(); }); functi ...