Encountering an infinite $digest() loop in AngularJS 1.4.8 while using ngOptions in a select when setting the model programmatically before the option is available in ngOptions

When upgrading from version 1.2.14 to 1.4.8, I encountered a problem that worked fine in the former but resulted in an infinite $digest() loop in the latter. To demonstrate this issue, you can view the following Fiddle. The Fiddle provides a clearer visualization of the problem discussed here.

The issue revolves around a select element defined as:

<select ng-model="selectedId" ng-options="opt.id as opt.label for opt in getOptions()">

This select element works with options structured as objects like:

$scope.options = [ { id: 1, label: 'one' }, { id: 2, label: 'two' } ];

The choice of options passed to the ngOptions directive is condition-dependent. At times, it may utilize only $scope.options, while at other times, an additional option needs inclusion.

$scope.getOptions = function() {
    if ($scope.showThirdOption)
        return [{ id: 3, label: 'three' }].concat($scope.options);
    else
        return $scope.options;
};

If the model is programmatically set to 3:

...
$scope.selectedId = 3;
...

Angular handles this without issues, adding an <option> node to the <select> element with a blank appearance in the dropdown.

However, setting conditions such that getOptions() returns the additional option:

...
$scope.selectedId = 3;
$scope.showThirdOption = true;
...

Resulted in an infinite $digest() loop.

An image illustrating the problem can be seenhttps://i.sstatic.net/8OFRY.png.

Are there any elegant solutions to avoid such complications? Is this possibly a bug in Angular (given that it's technically a regression) or simply a misuse of ngOptions?

To experiment and explore this issue further, feel free to visit the Fiddle provided.

Answer №1

The issue arises because the function getOptions() is being called directly in ng-options. To resolve this, create a new variable and store the value returned by getOptions(), then utilize this variable in ng-options:

$scope.newOptions = $scope.getOptions();

ng-options="opt.id as opt.label for opt in newOptions"

Additionally, remember to update newOptions when the button is clicked.

By following these steps, you should eliminate the problem of infinite digest loops. Check out the updated example on: http://jsfiddle.net/bbcjeuhb/

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

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

What is the most efficient way to use map-reduce in TypeScript to filter a list based on the maximum value of an attribute?

Recently, I came across a list that looked something like this: let scores = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}, {name: "D", skills: 60, ...

Is there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

Using Ajax and PHP to Trigger a Forced Download

I am trying to develop a download script that enables the Force Download of JPGs. Below is my PHP script: <?php header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ...

Retrieve data using Ajax querying from a specific data source

Currently, I am attempting to construct a custom query using Ajax to interact with PHP/MySQL. Here is what I have so far: Javascript code: var i=2; fetchFromDBPHP("name", "tblperson", "id="+i); function fetchFromDBPHP(column, table, condition) { ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

When you click on the submit button, it triggers the associated event

I have multiple text input fields where pressing the enter key should move focus to the next field. After reaching the last text input, I want the focus to be on the submit button without triggering its click event until the user presses enter again. The c ...

What is the proper way to halt an iteration with the $q service in AngularJS

Trying to incorporate the $q service to introduce a pause in the iteration due to a condition that requires making API calls within a loop. Implemented the following method: function fetchData(id){ var deferred = $q.defer(); var data; Restangula ...

What is the best way to retrieve the following database results after clicking a button with Node.js?

Currently, my Node.js setup is successfully connected to my webpage and pulling data from a MySQL database. I have managed to display the first row of data as button values in the HTML code below. However, what I now want is for the user to be able to cl ...

Making AJAX requests repeatedly within a loop

My current challenge involves implementing multiple ajax requests within a loop to populate several dropdown lists. Running the requests sequentially has resulted in only the last item in the loop being populated with values. var targetcontrols = []; ...

What is the best way to link this information to access the data attribute?

Currently, I am looking to streamline the data retrieved from firebase so that it can be easily displayed in a FlatList component. How can I transform my data into a simple array that can be iterated over in the FlatList? UPDATE! I have multiple other coi ...

Modify the color of the header on Material-UI Date Picker

I recently integrated a Material-UI Date Picker into my React Single Page Application and now I'm facing an issue with changing the header color. I attempted to modify it using the muiTheme palette property, but unfortunately, the header color remains ...

What is the best way to apply a jQuery function to multiple div elements simultaneously?

I am looking to implement a show/hide feature for a <div> using JavaScript and DOM properties. The idea is to use JavaScript's onclick() function with two buttons, show and hide, each in their respective <div>. Here is how it would ideall ...

Indexing text fields for MongoDB collection that have been populated

Currently, I am in the process of learning how to use indexing with Mongoose/MongoDB and I am facing an issue that I can't seem to resolve. This is the schema I am working with: const timeSchema = new mongoose.Schema({ actionId:{ type:St ...

Save the output of my Java function into a JavaScript variable

I have created a web application using JSP, CSS and HTML. The page contains six buttons, each of which calls a JavaScript method. For instance, the first button triggers the par() method. <html> <head> <title>Welcome d To Student Unive ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files. While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript bein ...

Finding the text within a textarea using jQuery

My journey with jQuery has just begun, and following a few tutorials has made me feel somewhat proficient in using it. I had this cool idea to create a 'console' on my webpage where users can press the ` key (similar to FPS games) to send Ajax re ...