Creating a custom AngularJS filter to search within an array of objects

I'm currently working with an object in my project:

{"A":[],"B":[],"C":[],"D":[],"E":[],"F":[{"name":"Fargo","id":29}],"G":[],"H":[],"I":[],"J":[],"K":[],"L":[],"M":[],"N":[],"O":[],"P":[],"Q":[],"R":[],"S":[{"name":"Sullivan","id":23},{"name":"Sven","id":26}],"T":[],"U":[],"V":[],"W":[],"X":[],"Y":[],"Z":[],"#":[]}

My goal is to create an angular js filter that filters the objects based on their name property. The idea is to display filtered results as the user enters each new character.

To achieve this, I have developed a custom filter:

app.filter('alphabeticSearch', function () {
    return function (obj, query) {
                if (!query) {
        return obj;
    }
    var filtered = {};
    for (var i = 65; i < 91; i++) {
        filtered[String.fromCharCode(i)] = [];
    }
    filtered['#'] = [];
    for (i in obj) {
        var _this = obj[i];
        filtered[i] = _this.filter(function (ele) {
            var reg = new RegExp(query, "gi");
            return reg.test(ele.name);
        })
    }
    return filtered;
    };
});

However, when implementing this angularjs filter, I encountered an error message:

[$rootScope:infdig] 10 $digest() iterations reached. Aborting!

This is how I am trying to utilize the filter feature in my HTML code:

<input type='text' id='cSearch' ng-model='ent' value='' />
<div ng-repeat="(letter,obj) in item | alphabeticSearch:ent">
   ....
</div>

Answer №1

One reason for this behavior is that your filter function creates a new instance of the object and query parameters each time it is called.

Angular evaluates the filter expression during each digest cycle to detect changes. So, on every digest cycle, Angular checks the result of your filter. If the filter function returns a different object or query parameter, Angular assumes there has been a change and attempts to re-evaluate the filter. This cycle repeats itself as the filter function continuously generates new objects, causing Angular to repeatedly re-evaluate until it reaches its limit and throws an exception.

To resolve this issue, you can make a few adjustments to your filter function:

app.filter('alphabeticSearch', function () {
    var filtered = {};
    var lastObj={};
    var lastQuery="";
    return function (obj,query) {
       if (!query) 
           return obj;
        if(angular.equals(obj, lastObj) && angular.equals(query,lastQuery))
            return filtered;

        lastObj = angular.copy(obj);
        lastQuery = angular.copy(query);
        filtered={};
        for (var i = 65; i < 91; i++) {
            filtered[String.fromCharCode(i)] = [];
        }
        filtered['#'] = [];
        for (i in obj) {
            var _this = obj[i];
            filtered[i] = _this.filter(function (ele) {
                var reg = new RegExp(query, "gi");
                return reg.test(ele.name);
            })
        }
        return filtered;
    };
});

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

Spring application: Unable to find a handler for portlet request with mode 'view' and phase 'Resource_PHASE'

It seems like everything is set up correctly, but for some reason, my ajax call fails with the error message "No handler found for portlet request: mode 'view', phase 'Resource_PHASE'". The handler URL I'm using is "getAllFruit", ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

Unable to retrieve obj after using $location.url

I am working with two different views. In the first view, I call a function from the admin controller using AngularJS: <a ng-click="updateAdmin(admin)">update</a> The code in the admin controller looks like this: $scope.updateAdmin = functio ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

The request made to `http://localhost:3000/auth/signin` returned a 404 error, indicating that

My goal is to access the signin.js file using the path http://localhost:3000/auth/signin Below is my code from [...nextauth].js file: import NextAuth from "next-auth" import Provider from "next-auth/providers/google" export default N ...

Importing JavaScript into an Angular component: A beginner's guide

Within my Angular-11 project, I have included the following JavaScript file: "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js", I have added it to the angular.json configuration as detailed above. import Stepper from '.. ...

What is the best way to initiate a local Node.js server specifically when launching a desktop Electron application?

I am looking to ensure that my node js server runs while my electron app is open. One method I have attempted is using the child_process module to execute a shell command as shown below: const {exec} = require('child_process') const startDBServ ...

Using Node.js: Interacting with npm inside a module

Is there a more efficient way to implement self-updating functionality for a globally installed module than using the code snippet below? require("child_process").exec("npm update -g module-name"); I came across some documentation regarding installing np ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

Steps to Change the Background Color to White in a Dropdown menu

Hello everyone! I'm currently using this codepen example on my website. My query is regarding the fifth panel - is it possible to change the color of the drop-down box when clicking on it? Here's a snippet of the HTML: <link href='https: ...

Exploring the functionality of Material-UI's TextField component through role-based testing with React

I currently have some components that contain mui TextFields, and there are two specific scenarios for these components: One TextField is meant for LicenseCode and does not require a label. Additionally, there are several TextFields generated using t ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

The ng-repeat function is currently disabled and not displaying any data from the JSON object

I am currently facing an issue where the ng-repeat Directive in my code is getting commented out and not displaying the results of the JSON object. I have verified that the object is being properly passed to "this.paises2" using the toSource() method, and ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

The issue arises when the view fails to load while simulating a backend

Trying to test a specific element of the user interface requires a particular request to the backend with predefined data while allowing all other requests to pass through. Here's a more readable version in coffee script: describe 'select2 combo ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Material-UI's style is taking precedence over other styles that have been defined

Introduction Last week, I posted a similar query which touched on the same issue. However, as the solution seems to be different this time around, I am revisiting it in a new thread. Check out the updated version of the CodeSanbox Example that reflects t ...

Access the value of a variable from a window resizing event and utilize it in a different

I have a carousel that I'm working with and am trying to figure out how to announce the number of currently visible slides when the "next" button is clicked. While I can see that on resize, the correct number of slides is being logged, I am strugglin ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...