What could be causing the "10 $digest error" to appear in my code?

My goal was to create a basic app that could detect the size of the browser and display it. But, I encountered an error message saying "Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!"

app.controller('AppCtrl',function($window,$scope){
$scope.windowHeight;
$scope.windowWidth;

$scope.getWindowSize = function(){
    return {
        h:$window.innerHeight,
        w:$window.innerWidth
    };
};

$scope.$watch($scope.getWindowSize,function (newValue,oldValue){
    $scope.windowHeight = newValue.h;
    $scope.windowWidth = newValue.w;
});
});

Here is my HTML Template:

<!DOCTYPE html> 
<html ng-app="size-util">
   <head>
      <title></title>
      <script src="angular.js"></script> <script src="colorBorder.js"></script> 
   </head>
   <body ng-controller="AppCtrl">
      <div color-border='blue'>Welcome!</div>
      {{windowHeight}} {{windowWidth}} 
   </body>
</html>

The structure above showcases my code but it seems like there's an issue. Was my approach with the $watch method incorrect? I can't seem to figure out where the problem lies. Any suggestions?

Answer №1

If you want to watch a function for its return value, keep in mind that using $watch may not work as expected if the function always returns a new object. This is because the comparison between old and new objects will always result in oldObj !== newObj, causing another digest cycle even when values don't stabilize.

To avoid this issue, only return a new object when any of its values actually change:

var windowSize = {};
function getSize(){
  var h = $window.innerHeight,
      w = $window.innerWidth;

  if (windowSize.h !== h || windowSize.w !== w){
    windowSize = {h: h, w: w};
  }

  return windowSize;
}

$scope.$watch(getSize, function(newVal){...})

It's important to note that this approach does not trigger a digest on its own, so simply resizing the window won't reflect any changes until something else triggers a digest cycle.

Answer №2

function calculateWindowSize() {
    return {
        height: window.innerHeight,
        width: window.innerWidth
    };
}

This function will always return a new object with the current window size.

$scope.$watch(calculateWindowSize, function(newValue, oldValue) {
    $scope.windowHeight = newValue.height;
    $scope.windowWidth = newValue.width;
});

In this context, newValue and oldValue refer to two distinct objects.

To enable deep watching, set the third argument of the $watch function to true.

$scope.$watch(watchFunction, listenerFunction, true)

Answer №3

It seems unlikely that you will be able to get it working smoothly (even if you manage to, the efficiency may be lacking).

The $scope.watch() function is used to monitor a variable's changes
. In this scenario, you are observing a function that remains constant and does not change. I recommend using a directive instead if you wish to track the window.resize event:

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

jQuery Multi-select - Event Handler for Selecting All Items

I am currently using a jQuery multiselect that has the select all option checked by default. When there is a change in the selected options, I reload the page data accordingly. Everything is working well except for the fact that clicking the 'Select ...

Prevent form submission using jQuery based on ajax response, or allow it to submit otherwise

After setting up some jQuery code to handle form submission, the functionality is working well when certain conditions are met. However, I am facing a challenge in allowing the form to be submitted if the response received does not match specific criteria. ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

Optimizing performance in Angular 1.5 by utilizing $interval and enabling the Garbage Collector to efficiently handle memory management

After observing silently for a long time, I've finally decided to speak up. My task is to continuously poll a server (via http get) and showcase the responses on the browser. The framework I'm working with is angular 1.5. However, I seem to have ...

How can I extract an array of objects from an array of arrays containing objects?

Here is the array I am currently working with: let findAllSegmentProjectMediaFilesXref = [ { it: 0, bt: 0, items: [ { mute: false, startPosition: 10, endPosition: 20, ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Is it advisable to perform unit testing on my JavaScript code?

I'm interested in exploring the potential value of using QUnit. However, I am completely new to testing, especially with JS, and don't know where to begin. I would appreciate any guidance on starting unit testing for an application that already ...

Incorporating Entrance Animations for Individual Elements within ngView Using AngularJS

Can each content within ngView be animated individually upon entering, rather than the entire View (div) itself? ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

Retrieve JSON data from a different controller or service method in AngularJS

Utilizing an API has been a key part of my project. I developed a service that interacts with the API, specifically focusing on two controllers: Team Controller and Player Controller. The Team Controller retrieves team information like team name, creation ...

Saving integer data retrieved from DynamoDB in a React Native application

I need to store a user's progress by saving a value in a DynamoDB. While storing the value is not difficult, accessing this value for use in my application has proven to be quite challenging. When using dynamoDBWrapper.getItem(params), where the para ...

Error found in Nuxt3 application when using locomotive scroll functionality

I'm working on a Nuxt3 project with Locomotive Scroll and GSAP (repository link: https://github.com/cyprianwaclaw/Skandynawia-Przystan). I'm facing an issue where, when I change the page from index to test and then revert back, the page doesn&apo ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...

How can I properly customize and expand upon a Material UI ListItem component?

I'm currently working with TypeScript version 3.4.5 and Material UI version 4.2. I have the following code snippet: interface MyItemProps { name: string; value: string; } function Item({ name, value, ...props }: ListItemProps<'li&apo ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

Tables inserted via ckeditor do not preserve the style attribute

After incorporating ckeditor into my web page along with the table plugin, I noticed that sometimes the width of tables created in the editor window extends beyond the boundaries of the webpage when displayed. To address this issue, I made some adjustments ...