Trouble with AngularJS: Updates not reflecting when adding new items to an Array

I am facing a persistent issue that I have been unable to resolve, despite researching similar problems on StackOverflow.

My current project involves building an application with the MEAN stack. However, I am encountering difficulties when trying to dynamically render new items using ng-repeat.

The application retrieves a large number of items from a MongoDB database through API calls successfully.

Initially, I need to display only 24 items, with an option for users to load an additional 24 items each time they click on a "show more" button. These newly fetched items should be appended after the existing ones.

The first set of 24 items renders correctly, but subsequent items do not appear on the page.

When I log the newly fetched items, I can see their attributes without any issues.

Below is a condensed version of my items View:

<div class="myItem" ng-repeat="item in searchCtrl.items track by $index">
  . . . .
</div>

This is the Show More Button:

<a class="showMoreButton" ng-click="searchCtrl.goToNextPage()">show more</a>

Here is a simplified snippet of my Controller (aka searchCtrl):

function SearchController($scope, ItemFactory) {
  // Controller logic here...
}

Similarly, this is a simplified version of my ItemFactory:

angular.module('myApp').factory('ItemFactory', 
                function ($http, API_URL) {
  // Factory code here...
});

My Controller bindings and routing are working as expected by following a modularized approach.

In attempts to solve the rendering issue, I also considered using the concat method instead of looping through items, but the result remained unchanged.

Main Issues:

  • Only the initial 24 items are rendered properly.
  • Subsequent items beyond the first 24 fail to show up in the DOM, even though they are added to the items array.
  • Attempts to use $scope.$apply(); resulted in digest errors.

Queries:

  1. What could be causing this problem?
  2. How can I address this rendering issue effectively?

Any assistance or clarification would be greatly appreciated. Feel free to leave your comments below. Thank you!

Answer №1

By implementing a solution that involves broadcasting a message from ItemFactory when fetching new items and adding a listener to that message in SearchController, I was able to resolve this issue. When the broadcast event ItemDataRefresh is triggered, the SearchController then appends the new data accordingly.

ItemFactory:

function getItems(params) {

    return $http.get(API_URL + '/item',{params: params}
    ).then(function success(response) {
        $rootScope.$broadcast('refreshData', response.data);
        return response;
    });
}

SearchController:

function fetchItems(){
    ItemFactory.getItems(vm.searchParams).then(function(response){

      //When vm.items is empty
      if (!vm.items.length) {
        vm.items = vm.items.concat(response.data.data);
      }

      //on refreshData
      $scope.$on('refreshData', function(event, data){
        vm.items = vm.items.concat(data.data);
      });

    }, function(error){
        $log.error(error);
    });
}

Although I am aware that using $rootScope is not best practice, I am still exploring alternative methods to achieve the same functionality more cleanly.

I trust that this explanation will be beneficial to someone facing a similar challenge.

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

JavaScript: Closing a Tab

Using AngularJS for my project and I have a link that opens a tab. If the user right clicks on the link and selects open link in new tab, then on the page abc.html I have code like $window.close(); which is not working as expected. I am receiving the error ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Angular select automatically saves the selected option when navigating between views

I would like the selected option in my dropdown menu to stay selected as I navigate through different views and then return back. Here is the view: <select ng-model="selectedSeason" class="form-control" ng-options="season as 'Season '+ seas ...

How can I deactivate the main color of the FormLabel when the focus is on the radio button group?

Is there a way to change the color of FormLabel to black instead of the primary color when the radio button group is focused? const styles = { formLabel: { color: "#000" }, formLabelFocused: { color: "#000" } }; function App({ classes } ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

Generate responsive elements using Bootstrap dynamically

I'm having success dynamically generating bootstrap elements in my project, except for creating a drop-down menu. ColdFusion is the language I am using to implement these div elements: <div class="panel panel-primary"><div class="panel-head ...

Utilizing HTML Elements for Conditional Statements

I had a question regarding HTML code and JavaScript functionality that I came across while honing my coding skills. My curiosity lies in understanding how an HTML element can act as a boolean condition within a JavaScript while loop. Take, for instance, ...

Is the current version of NPM React-router too cutting-edge for your needs

When I use the command npm -v react-router on my React app, it shows version 6.9.0. However, when I check the npmjs page for react-router, the latest version available is 5.0.1. How can this discrepancy be explained? ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

What are the steps to resolve the TypeError related to reading 'split' on mongoose when properties are undefined?

Just successfully connected mongoDB with mongoose, but encountered an error stating TypeError: Cannot read properties of undefined (reading 'split'). How can I resolve this issue? Below is the code snippet: export const dbConnect = async () => ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...

What exactly does <T> signify within the realm of dynamic forms?

Currently, I am experimenting with the Angular2 cookbook instructions for Dynamic Forms. The instructions mention: export class QuestionBase<T>{ value: T, ... I am confused about the purpose of the "<T>" in both instances. Do you have any ins ...

Steps for inserting a video into a new div upon selecting a hyperlink

Looking for a way to link menu elements to corresponding videos in adjacent divs? I have two divs set up - one with the menu list and another right next to it where the videos should be loaded. Forms seem like a potential solution, but I lack expertise i ...

Creating a custom component results in an extended duration to 'eliminate' its children

1I am currently facing an issue with a time-table component created using vue.js. It contains approximately 200 nested child timeline components, making it quite complex (I wanted to share an image but lacked the reputation to do so). The main problem lie ...

webpackDevMiddleware does not automatically trigger a reload

Currently, I have implemented webpack dev middleware in my project like this: const compiledWebpack = webpack(config), app = express(), devMiddleware = webpackDevMiddleware(compiledWebpack, { historyApiFallbac ...

Appium with Node.js (wd) becomes unresponsive when unable to locate element

Encountering an issue while using appium with nodejs (wd) and mocha, as there is a loading view in the android app (blackbox testing & I'm not the developer) that needs to be waited for its disappearance. Attempted the following solution: wd.addPromi ...

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Seeking assistance for my dissertation assignment: electron, express, and SQLite3

I am currently dedicated to my thesis project, which involves designing an educational desktop video game for both public and private schools within my city. Being a fan of electron, I thought it would be a great idea to develop my app using this platform ...

Discover the following `<td>` identifier through the act of clicking on a separate `<td>` element

I have a few td's with specific ids: <td id="first">first</td> <td id="second">second</td> <td id="third">third</td> <td id="fourth">fourth</td> Whenever I click on one of the td elements, I want to re ...