AngularJS is encountering infinite digest errors from a $watch function that does not actually trigger any modifications

Within my AngularJS script, I have a single $watch function as shown below:

$scope.$watch('[p, q]', function(newVals, oldVals) {
    $scope.n = newVals[0] * newVals[1];
    $scope.phi = (newVals[0] - 1) * (newVals[1] - 1);
});

Despite the fact that the function does not alter either p or q, it is throwing an infdigs error. Why could this be happening?

Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.0-beta.5/$rootScope/infdig?p0=10&p1=%5B%5B%…%20q%5D%3B%20newVal%3A%20%5B5%2C7%5D%3B%20oldVal%3A%20%5B5%2C7%5D%22%5D%5D
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:6:456
    at h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:107:164)
    at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:109:287)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:18:23
    at Object.d [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:34:211)
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:17:439)
    at cc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:18:140)
    at ed (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:17:215)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js:212:459 angular.js:9784
Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.0-beta.5/$rootScope/infdig?p0=10&p1=%5B%5B%…%5B5%2C7%5D%22%5D%2C%5B%22%5Bp%2C%20q%5D%3B%20newVal%3A%20%5B5%2C7%5D%3B%2...<omitted>...5D angular.js:12453

UPDATE: Additional relevant code

app.controller('RSACtrl', function($scope) {
    // These lines just define default values, correct?
    $scope.m = 'Hats are cool.';
    $scope.p = 5;
    $scope.q = 7;
    $scope.n = $scope.p * $scope.q;
    $scope.phi = ($scope.p - 1) * ($scope.q - 1);
    $scope.e = 17;
    $scope.d = inverse($scope.e, $scope.n); // Computes modular inverse in a purely functional manner.
    //

    $scope.$watch('[p, q]', function(newVals, oldVals) {
        $scope.n = newVals[0] * newVals[1];
        $scope.phi = (newVals[0] - 1) * (newVals[1] - 1);
    });
}

A snippet of HTML

    <label>Enter a prime p:</label>
    <input type="number" ng-model='p'>
    <br/>
    <label>Enter a prime q:</label>
    <input type="number" ng-model='q'>
    <br/>
    <p ng-show='isPrime(p)'> p = {{p}} </p>
    <p ng-show='isPrime(q)'> q = {{q}} </p>

The {{}} placeholders do not assign any values

Answer №1

When using the watch function, the first parameter is an expression that gets evaluated within the scope context. In your case, the expression is [p, q], which creates a new array each time it runs. This causes a new digest cycle to be triggered, resulting in an infinite loop. If you simply want to execute the logic whenever either p or q changes, you can watch them separately and call the same function.

function doStuff(p, q)
{
    $scope.n = p * q;
    $scope.phi = (p - 1) * (q - 1);
}

$scope.$watch('p', function(newVal) {
    doStuff(newVal, $scope.q)
}
$scope.$watch('q', function(newVal) {
    doStuff($scope.p, newVal)
}

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

Error in Charts API - [draw function failed to render for one or more participants]

Currently encountering an error on the client side where one or more participants failed to draw. I am able to successfully output data in the drawVisualization call, indicating that the issue lies within the JavaScript code. Despite following examples, I ...

The function ng-hide is not successful at concealing the button

I am trying to implement logic where the button is hidden if it pertains to deleting a folder, but shown if it's related to the inbox. However, the code provided below does not seem to be working as expected, as the button always appears. <div cla ...

I'm currently experiencing an issue where I am not receiving the Validation Flash Message in the UI. Instead, I am seeing a flash error displaying as [object Object],[object

I am currently developing a Blog application using NodeJs, where I have integrated express Validator to validate data. I am facing an issue with displaying flash messages in the UI after submitting forms. The error message that I receive is [object Object] ...

Choosing not to transmit the requested file

I've been attempting to retrieve the following: fetch("https://www.filestackapi.com/api/store/S3?key=MYKEY&filename=teste", { body: "@/C:/Users/Acer/Pictures/1 (2).jpg", headers: { "Content-Type": &quo ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Storing Information in a Two-Dimensional Array using JavaScript

Looking to loop through the Data array and indicate with an "O" if it contains the specified Month and Number. For example, for "Jan-1", Array1[0][0] should be set to "O". However, the code provided below is not working as expected. Any assistance would ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

The Bootstrap accordion feature or show/hide function is experiencing issues when dealing with dynamically created elements in jQuery

When interacting with items in my sample application, a pop-up displaying the item's description should appear. However, attempts to use Bootstrap accordion or hide and show features were unsuccessful, only jQuery delegate event handlers worked. In g ...

Using ng-model to create association between a select box and ng-repeat to populate its options

Here is a Plunker link demonstrating my problem. I have an object that includes a division property. The issue is, there is no division_id in the object, but to set or update the division, I need to set the division_id field. Here's an example of the ...

How does a JS event impact the state transition in a backend state machine built on Rails?

I am currently developing a new project where the backend involves Users who have multiple "Courses" each containing multiple "Steps". My goal is to create a JavaScript function that validates the user's answer. For example, if the user inputs "6", w ...

Exploring the benefits of thrift integration in Angular 2

Currently, I am working with the thrift protocol and have developed a basic app using Angular2. I create .js files by running thrift --gen js:ts file.thrift. Can anyone provide guidance on integrating Thrift into an Angular2 application? ...

Validating radio buttons in JS after submitting a form using PHP $_POST

I am dealing with a form that contains a variable number of radio buttons: <input id='create' name="post[]" type="radio" value="<? echo $newphrase; ?>" /> My goal is to validate the form to ensure that at least one button is select ...

Utilizing PHP loops with the integration of a Datetimepicker

When using datetimepicker javascript for bootstrap, I encountered an issue where the instance works fine if there is only one input field or if it's the first of multiple fields. However, when there are multiple fields, the datetimepicker does not wor ...

passing data from the view to the controller

When I choose an option from the dropdown menu, the selected value is not being passed to the controller action method. Although the selected value is binding in Ajax, it is not binding in the controller action method. Check out our page <div class="ro ...

Tips on saving all objects, even those that are repeated, in a JavaScript array

My goal is to store and display all objects, even if they are repeated, but the current setup only allows for storing unique values. The positive aspect is that it calculates the total by summing up all values, including duplicates. The Negative aspect is ...

Moving a div on key press can be accomplished using a combination of HTML, CSS

I am currently working on an HTML game where the player can navigate around the webpage. However, I am encountering issues with getting the movement functionality to work. My goal is to have the player move when certain keys are pressed. While I was able t ...

Mastering the art of utilizing Context API and Provider for optimal functionality

Currently, I am working on implementing a dark mode feature in my project. Despite everything appearing to be set up correctly, it seems like the Context at App is not re-rendering when I use the setTheme function inside the Provider. Can someone help me t ...

Using functions like .map in a TypeScript model may not function properly

After retrieving data from a server, I created a TypeScript model to structure the incoming data as follows: export class DataModel{ public PageNo: number public showFromDate: string public showToDate: string public gradeFieldId: number } ...