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

Triggering the onClick event in React to invoke another class components

I'm currently working on implementing a modal popup (stored in the PostView class) so that it appears when any post in the postcontainer class is clicked. As I am new to React, I would greatly appreciate any suggestions for enhancing the code. Post C ...

Verify whether the document includes a class that closely matches the provided string using Javascript

I need help identifying elements that include the letters 'ad'. For example: <iframe class="container" /> <!-- Not relevant --> <a class="adp" /> <!-- Relevant --> <a class="adleft" /> ...

What is the best way to preserve the state of child components after being filtered by the parent component?

I've been working on a small application using create react app to enhance my skills in React, but I've hit a roadblock with managing the state. The application maps through JSON data in the parent component and displays 6 "image cards" as child ...

display the fieldset based on selected dropdown option

In my form, I have 5 different products with attributes. I want to display only one product field-set when the user selects from a dropdown menu and increments. $scope.choices = [{id:'choice1'},{id:'choice1'},]; //Function to add a ne ...

Convert data into a tree view in JavaScript, with two levels of nesting and the lowest level represented as an array

Here is an example of a JSON object: [ { "venueId": "10001", "items": [ { "venueId": "10001", "locationId": "14", "itemCode": "1604", "itemDescription": "Chef Instruction", "categoryCode": "28", ...

Tips for efficiently handling navigation re-rendering on a Single Page Application using Vue.js

I am currently in the process of developing a Single Page Application using Vue.js. The structure involves having a template in App.vue which includes a navigation bar followed by a router-view component. When a user attempts to log in, a modal window appe ...

Paypal Payment Plans on a Monthly Basis Utilizing the Bootstrap Pricing Slider

I came across this fantastic Bootstrap Pricing Slider that I found originally at Within my Bootstrap Pricing Slider, there is a "total amount" calculated after some math, resulting in a final score. The slider includes a "Process" button which currently ...

Issue with table display within <div> element in React

Recently diving into React, I find myself in a situation where I need to display data in a table once it's ready or show 'Loading' if not. Currently, my render() function looks like this: return ( <div> { this.state.loaded ...

What steps can I take to ensure that I establish the definition of this variable?

My situation involves a variable called Blog, which is a mongoose model. The definition of this variable is as follows: db.once("open", function(){ var userSchema = new mongoose.Schema({ username: String, password: String }); ...

Altering the language code on LinkedIn

As a beginner in programming, I successfully added the linkedin share button to my test webpage. Now, I am hoping to make the button change language based on the user's language selection on the webpage. Linkedin uses a five character language code ( ...

Error message: The variable datepicker_instActive is not defined within Jquery-ui Datepicker

Having trouble with a Rails + Angular app where I've implemented the jquery-ui datepicker. The console is showing an error that says: TypeError: datepicker_instActive is undefined if(!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? ...

Ways to set a default image for an <img> tag

I am looking to set a default image to the img tag in case the user has not selected a profile picture for their account. Here is the current output: http://jsfiddle.net/LvsYc/2973/ Check out the default image here: This is the script being used: funct ...

Exploring hierarchical information within a JSON response from a Wiki API

As a newcomer to this field, I am currently exploring ways to access Wikipedia's API for extracting the value of "extract" and adding it to an HTML element dynamically. The challenge lies in the fact that the information is subject to change based on ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

Creating a wrapper function for the map method in React

When attempting to incorporate a parameter into my map function in React, I encountered an issue where the return value turned null after encapsulating it within another function. This became apparent during debugging, especially when using console.log(mar ...

How do I retrieve and pass values from multiple inputs in my React application?

I've implemented the <autocomplete> as an input field, and I'm currently troubleshooting my submit method by logging values to the console. Unfortunately, I can only submit empty data to my axios instance without any Traceback errors for gu ...

Can you elaborate on the users object found in the npm registry JSON response?

When looking at the json response of any npm package, such as jQuery for example, http://registry.npmjs.org/jquery, you may come across a dictionary called users. This dictionary contains usernames as keys and boolean values as the corresponding values. ...

Transmitting a vast amount of data through a single stream using NodeJS and ExpressJS

I am currently in the process of creating a prototype for an application using the native mongo rest api. In this scenario, Node returns approximately 400K of JSON data. To make the request to mongo's native API and retrieve the result, I am using the ...

What is the best way to show a dropdown menu on the right side of the

I developed a demo that functions properly on both desktop and mobile devices. However, I am facing an issue where the dropdown menu is not displayed when switching to the mobile version. Here is my code snippet: http://codepen.io/anon/pen/OyNLqa ...

Tips for incorporating additional filter criteria into a jquery script

I am currently utilizing a jQuery script to filter data based on date periods. However, I now need to include an additional filtering criteria for the "POSITION" column. Since I lack expertise in jQuery, I would rather accomplish this using plain vanilla J ...