Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices.

angular.module('abc').filter('searchFor', function(){
return function(array, searchString){
var arr =[]
  if(!searchString.length){
    return array;
  }
  var result = [];
  for(var i=0;i<array.length;i++){                    
  //put all devices of all device Groups into arr
  var temp = array[i].devices
    for(var j=0;j<temp.length;j++){
      arr.push(temp[j])
    }
  }
  // search in tags of arr individual searchString
  for(var i=0; i<searchString.length;i++){
    searchString[i] = searchString[i].toLowerCase()
    var res = []
    for(var k in arr){
      //there are some tags in device data object so I am searching in the same
      var tags = arr[k].tags
      tags.push(arr[k].ID)
      tags.push(arr[k].Name)
      tags.push(arr[k].Type)

      for(var j in tags){
        if(tags[j].toLowerCase().indexOf(searchString[i]) !== -1){      
          // if tags matches with searchString push it in res
          res.push(arr[k]);
          break;     
        }
      }
      result[i] = res                   
    }
  }
if (result.length > 1) {
    result.sort(function(a,b) {                     
    return a.length - b.length
  })
  for(i=0;i<result.length-1;i++){
    var a = result[i]
    var b = result[i+1]
    var common = []
    for (var j = 0; j < a.length; j++) {
      for (var k = 0; k < b.length; k++) {
        if (a[j].ID == b[k].ID) {
          common.push(b[k])
          break;
        }
      }
    }
    result[i+1] = common
  }
  resultFinal = common
}else {
  resultFinal = result[0]
}
/* Finally resultFinal contains the devices satisfying the search 
criteria
 Before returning back group all the devices according to their 
device types in deviceGroups(data Structure is as mentioned in demo 
output) */
  return deviceGroups
}
})

The purpose of this code snippet is to categorize an array of devices based on their 'type' parameter. Each device type has its own array of devices. However, there seems to be an issue causing an infinite digest loop.

Here are examples of input and output:

$scope.device_data = [
    {name: 'D_1', type: 'wmeter'},
    {name: 'D_2', type: 'fmeter'},
    {name: 'D_3', type: 'smeter'},
    {name: 'D_4', type: 'fmeter'}
]

The desired output should be organized like this:

[
    'watermeter': [
        {name: 'D_1'}
    ],
    'flowmeter': [
        {name: 'D_2'},
        {name: 'D_8'}
    ],
    'solar': [
        {name: 'D_3'}

    ]
]

HTML snippet:

<div ng-repeat="group in deviceGroups | searchFor: searchString">

    <h2>{{group.type.toUpperCase()}}</h2>

     <div ng-repeat="device in group.devices">
         <p>{{device.name}}</p>
     </div>
</div>

Answer №1

An age-old issue arises with the infinite digest glitch, often brought on by the ng-repeat function looping through an ever-changing array reference. Angular's diligent checks during this process mean that a new, distinct array reference will trigger an endless loop.

The culprit? Your filter is generating fresh array instances each time. The solution lies in modifying the current array instead of presenting a whole new one. Time to revamp your filter and avoid the eternal digestion cycle!

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

Show JSON response using AJAX jQuery

After receiving the JSON Response, { "user_data": { "id": 22, "first_name": xxx, "last_name": xxx, "phone_number": "123456789", }, "question_with_answers" : [ { "id": 1, ...

Is there a way to customize the appearance of a MUI5 Tooltip using emotion?

I went through the information in this Stack Overflow post and experimented with the styled method. The code snippet I used is as follows: import * as React from 'react'; import { styled } from '@mui/material/styles'; import Tooltip, { ...

The overlay background is being obscured by surrounding elements

Hey there! I'm experimenting with some basic coding and ran into an issue with an overlay. Here's the site link: Sorry for the strange language. :-) If you click on the button with the tiny icon, you'll notice that the overlay form isn&apos ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

Secure HyperText Transfer Protocol prevents JavaScript from executing

My website's HTTPS version is having trouble loading JavaScript. All scripts are hosted on the same server. I've attempted: <script type="text/javascript" src="https://server.tld/js/jquery.js"> <script type="text/javascript" src="//ser ...

What is the best way to incorporate parallax scrolling in the center of a webpage?

I am trying to implement a parallax scrolling effect in the middle of my page, but it seems to be causing issues once I reach that section while scrolling. I attempted to use intersection observer, but unfortunately, it did not resolve the problem. const ...

How to dynamically change the position of an input field within a form using JavaScript and jQuery

I have a form displayed on my website that looks like this: input a input b input c I am wondering if it is achievable to rearrange the order of inputs using jQuery, like so: input a input c input b However, it is important that the data is still ...

Issue with changing the opacity of a Javascript button style is not functioning correctly

The button's opacity used to change gradually in increments of 0.1 every 500 milliseconds, but now it instantly changes to 0.9 without the delay. Issue: Despite being placed within a window load handler and all elements loading properly, the loop is ...

Having some trouble using ionic's `on-swipe-right` method to modify states. Can't seem to get past this error

Apologies for the frustration, I've been trying to resolve this issue for the past few hours. I attempted to navigate to a new state without passing parameters in order to progress, but unfortunately, it hasn't worked out! THE ERROR. Error: C ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array. This is how the string value appears in the csv file: "Tiger","Architect","800","DRP","5421" ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...

Menus that mimic the style of Google Translate's select options

I'm looking to design an HTML select menu using CSS in a similar fashion to Google Translate's style on Google Translate. I've searched for tutorials online, but they all involve jQuery. Is there a way to achieve something similar using only ...

Attempting to create a slider utilizing jQuery

I'm currently working on creating a slider using jquery. I have downloaded the cycle plugin for the slider and included it in my file. The slider consists of 7 pictures. Below is the code I am using, can someone please help me identify any issues? &l ...

Exploring the implementation of waterfall in a Node.js application

async.traverse(map, function(item, tnext){ async.waterfall([ function(wnext){ console.log("One"); //performing MongoDB queries db.collection.find().toArray(function(err){ if(err){ ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

Is there a way to pass a c struct pointer into javascript using ffi?

I need help passing a pointer to a struct to a method in nodejs using ffi. I am encountering an error where the type of the JavaScript struct I created cannot be determined. How can I resolve this issue? Previously, I was able to successfully implement si ...