Angular constantly looping due to $watchCollection being triggered repeatedly

I am interested in monitoring the changes of an object, referred to as x, specifically its properties which are checkboxes. When a user checks a box, it alters the checked property (prop1) to 1.

Each property contains certain content, and when enabled, it should expand the height of the containing element to accommodate that new content.

        $scope.x = {
            prop1: 0, 
            prop2: 0,
            prop3: 0,
            prop4: 0,
        };

I have set up a watch function to track any modifications made to x. If there are changes, the element's height is adjusted:

    $scope.$watchCollection('x', function(embed){
        $scope.x.height = $scope.getHeight();
    });

The method getHeight is invoked, triggering checkOptions() to add specified buffer space to the element:

    $scope.getHeight = function () {
        $scope.checkOptions();
        return Math.ceil(($scope.totalElements / $scope.totalCols) * elementHeight);
    };

    $scope.checkOptions = function () {
        if ($scope.x.prop1 === 1) {
            elementHeight += 50px;
        }
        ...other properties

The HTML includes a checkbox for detecting true/false values:

        <fieldset class="modal-checkbox">
            <input type="checkbox"
                   id="element-prop1"
                   ng-model="x.prop1"
                   ng-true-value="1"
                   ng-false-value="0">
            <label for="element-prop1">
                <span>Element Prop 1</span>
            </label>
        </fieldset>

Upon clicking the checkbox, it continuously increases the height until:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":39,"oldVal":38},{"msg":"fn: expressionInputWatch","newVal":"6168","oldVal":"6006"}],'

After researching Angular $watchCollection, it appears to serve my purpose correctly by monitoring the collection within the x object for changes...

and according to $digest:

It processes all watchers of the current scope and its children. Since a watcher's listener can alter the model, $digest() keeps calling the watchers until no more listeners are triggered. This could lead to an infinite loop.

I am uncertain why I am experiencing this looping issue.

Answer №1

The issue lies in your watch function. Every time you modify $scope.x.height, it triggers the watch again because it detects a change in x.

To fix this, consider moving the height property out of x and placing it elsewhere. Alternatively, make sure that the value remains consistent regardless of how many times you call getHeight().

Also, keep in mind that when using ng-true-value or ng-false-value, the value will be treated as a string.

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

Turn off javascript on a website that you are embedding into another site

Is it feasible to deactivate JavaScript on a website you are attempting to embed? If the website is working against your embedding efforts, could you effectively neutralize all their JavaScript, even if it requires users to engage with the site without J ...

The event listener attached to this model is failing to trigger when there are

The issue is that the "change" event is not being triggered in the code snippet below. var PageView = Backbone.View.extend({ el: $("body"), initialize: function(){ this.model.on("change:loading", this.loader, this); }, loader: func ...

Can someone explain the significance of '{}' within the function shown below?

I've been able to grasp most of this code, but I'm unsure about "{}". Can anyone clarify its meaning? var Toggle = function(section, expand) { this.section = section || {}; this.expand = expand | ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

What is the correct way to define a function parameter when using AngularJS Emit?

I've been exploring the emit feature in AngularJS and had a question about passing a function as an argument. In the Parent Controller: $scope.$on("getChildFunction", function(event, func) { console.log("The function is...", func); }) In the Ch ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

What sets apart the npm packages @types/express and express?

Can't decide whether to use @types/express or express for building a node server? Take a look at the code snippet below: 'use strict'; const express = require('express'); const http = require('http'); const path = requir ...

Ways to show a component based on a specific condition being met using react and javascript

On every page, the layout component is rendered. My goal is to achieve the following: on /items page *Display Layout component only if user is admin *Do not display Layout component if user is non-admin Below is my code snippet: function Main() { con ...

Combine two columns into a single table column using HTML/CSS and JavaScript with the help of Datatables

I utilize the DataTables library from https://datatables.net/ to create sortable and searchable tables on my website. However, my table becomes too wide due to the numerous columns it contains. I am looking for a way to condense the width by merging relate ...

Tips for accurately measuring the height of a single table cell

I am facing an issue with a table that I have set up. Here is the code: <table> <tr> <td id='tdleftcontent' style='border:1px solid red;'> <asp:Label ID='lbl' runat="server"></asp:Label> < ...

Dealing with errors in multer and express-validator aspects

Is there a way to validate a form that includes an image using multer and other fields with express-validator? I keep encountering an undefined error (req.validationError) in the post route. Any suggestions on how to resolve this issue? server.js const e ...

Troubles arise when trying to load AngularJS using RequireJS within the application

I am currently developing a NodeJS application that utilizes AngularJS for its front-end. Additionally, I am integrating RequireJS to handle the loading of JavaScript dependencies and then initialize the Angular app. Here is my approach: Inside my HTML fi ...

Is it possible to utilize Angular.js as a full substitute for a traditional JavaScript template engine?

While angular excels in two-way data binding and single-page applications, could it also serve as a viable replacement for a JavaScript template engine? Let's dive into the potential pros and cons of this approach. ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Choosing multiple images by clicking on their alternative text with jQuery

I am currently working on a project that involves clicking on a thumbnail to enlarge the image and display its name (alt) below it. I have made progress, but there seems to be an issue where only one image is displayed no matter which thumbnail I click on. ...

Exploring the process of iterating through a JSON response in PHP to extract all values

{ "ver":2, "inputs":[ { "sequence":4294967295, "witness":"", "prev_out":{ "spent":true, "tx_index":372805487, "type":0, "addr":"3AFgA1pHKrk4jFHwzUL1CKgZvXyFSWZfgD", "value":12712, ...

Date Object Replacement Error: "this is not a valid Date object."

For my web application, I require a specific date value. I attempted to modify the Date prototype, but encountered an issue with Jquery Date recognizing it. InitDate = Date; InitDate.prototype = Date.prototype; Date = function () { if (arguments.leng ...