Trouble with updating the view when an array is modified in ng-repeat? It seems like using $scope.$apply() may not

When updating the array inside a function, the view does not automatically update. However, if you use console.log to check the array after pushing values, it shows the updated array. Even trying $scope.apply() inside $timeout did not solve this issue.

JavaScript:

$scope.openQuestions = [];

$scope.openQuestions.push({value: '1', question: 'abc1'});

$timeout(function() {        

  $scope.$apply(function() {            
    $scope.fetchOpen();      
  });

}, 500);

console.log($scope.openQuestions); //shows the updated value

$scope.fetchOpen = function() {
  $scope.openQuestions.push({value: '2', question: 'abc2'});
}

Html

<ul>
 <li ng-repeat = "question in openQuestions">
 <p>{{question.question}} </p>
 </li>
</ul>

Result: abc1

Answer №1

The issue arises from the utilization of the Array.prototype.push function:

 $scope.openQuestions = $scope.openQuestions.push({value: '2', question: 'abc2'});

As mentioned in the documentation:

The push() method appends one or more elements to the end of an array and provides the new length of the array as a return value.

It delivers the length of the array which is then assigned back to the reference variable containing the array, causing it to be overwritten.

Instead, simply use the push method without reassigning the array:

$scope.fetchOpen = function() {
  $scope.openQuestions.push({value: '2', question: 'abc2'});
}

Answer №2

@Sunny Kumar Are you using the code exactly as posted, or did you modify it before sharing it here? I had a similar issue where my ng-repeat statement was not updating properly. I was experimenting with different examples that worked fine until I realized that my problem was related to not initializing one of the attributes in my data file. After loading the data, I forgot to initialize this attribute which caused me to always get an empty list. Make sure to check all your attributes and ensure they are properly initialized after any changes to your array.

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

Is it possible to use Javascript to retrieve a variable from a remote PHP file?

I am trying to retrieve a variable from a remote PHP file using JavaScript in my phonegap application. The same origin policy doesn't apply here, so I believe I need to use JSON/AJAX for this task. However, I have been unable to find any tutorials tha ...

Handlebars: The property "from" cannot be accessed because it is not an "own property" of its parent and permission has been denied

My backend is built on Node.js and I am using server-side rendering with handlebars. I have a `doc` array of objects in handlebars that contains keys "content" and "from". However, when I try to loop through this array using `#each`, I encounter the error ...

Challenges involving memory allocation with a two-dimensional array

While studying how to dynamically generate a 2D grid (two dimensional array) of int values, I came across this helpful example that inspired me to create a function for the same. Initially, the function works fine when changing the values, but eventually ...

Waiting for asynchronous subscriptions with RxJS Subjects in TypeScript is essential for handling data streams efficiently

Imagine having two completely separate sections of code in two unrelated classes that are both listening to the same Observable from a service class. class MyService { private readonly subject = new Subject<any>(); public observe(): Observable&l ...

Service Worker unable to register due to an unsupported MIME type ('text/html') declared

Working on a project using create-react-app along with an express server. The pre-configured ServiceWorker in create-react-app is set up to cache local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README ...

Creating a four-dimensional array in PHP can be achieved by nesting multiple arrays within each

When I run a distinct query, I end up with a lot of data. Take a look at this picture of a busy cat: My goal is to group the final status by nodeid, portid, and total, which represents the total status. I need to create an array that looks like this: [ ...

Using Tinymce to automatically send form on blur action

Attempting to trigger form submission upon blur event in Tinymce, but encountering difficulties. tinymce.init({ selector: 'textarea.html', menubar:false, force_br_newlines : true, force_p_newlines ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

Arranging xCharts based on the weekday order

Struggling with xCharts, specifically trying to display a bar chart showing numbers with corresponding days of the week in order. Despite my efforts, I can't seem to get them to appear in the correct sequence. Refer to the image below for reference: ...

Challenges with CSRF tokens in Express

I am struggling to set up CSRF protection using csurf and express. My application utilizes Angular on the front end, so I believed that adding the following to my app would suffice: app.use(cookieParser('test secret')); app.use(cookieSession({ ...

JS filter function is not functioning as expected. It's unclear what the issue might be

Check out my previous inquiry What could be the issue with my filter? I've implemented a filter, but it seems to have some glitches when dealing with specific values. The 'No Record Found' message doesn't appear as expected in certain ...

Deregister channel listener

My application has a functionality where users can subscribe to Twilio chat channels. When a user clicks on a channel, the chat opens up, messages are loaded, and the user is subscribed to receive new messages using this.state.channel.on('messageAdded ...

Create an illustration of a canvas interacting with a database image source, but failing to display local images

When attempting to load an image onto a canvas, I encountered an issue. My code works without any errors when I use image.src="https://somelink", but throws a GET error when I try to import with image.src="../public/vercel.svg. Below is my c ...

What is the best way to insert images into a database?

I am currently working on an internship project that requires me to include an image when adding an employee to my table. https://i.stack.imgur.com/xif58.png https://i.stack.imgur.com/wDkY7.png We are using AngularJS on the front end and ASP.NET Core 3. ...

Having trouble with the second Angular directive not functioning correctly

I am encountering an issue with two directives on the same page. The first directive is functioning correctly, but the second one is not working as expected. Below is the code snippet: HTML <body class="login" ng-app="Login"> <div ng-controller ...

Creating a chart with multiple series in canvas js through looping

I'm currently working on creating a multi-series chart using Canvasjs. I've encountered an issue where I can't include a loop inside the dataPoints and have had to manually code everything. Is there a way to utilize for loops in this scenari ...

Utilizing a CSS/HTML div grid to mirror a 2D array in JavaScript

Currently, I am working on a personal project that involves creating a grid of divs in HTML corresponding to a 2D array in JavaScript. However, I am uncertain about the most effective way to accomplish this task. Specifically, what I aim to achieve is tha ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

Conceal the loading image once the AJAX function has been successfully

I've been trying to figure out a way to load heavy images after an ajax call using animated GIF as a pre-loader, but haven't found a satisfactory solution yet. Here's the code snippet I'm currently using: function loadProducts(url) { ...

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...