Reset an Angular service's public variable

I recently started working with Angular and encountered an issue that I couldn't find a solution for on Google or Stack Overflow. I believe my problem lies in not knowing what to search for. Here is the code snippet causing trouble: JSFiddle

HTML

<button ng-click="reload()">Reload</button>
<button ng-click="loadMore()">Load More</button>
<ul>
    <li ng-repeat="item in list">{{ item }}</li>
</ul>

JavaScript

var app = angular.module('app', []);

app.controller('mainCtrl', ['$scope', 'mainSvr', function ($scope, mainSvr) {
    $scope.list = mainSvr.list;
    $scope.reload = mainSvr.reload;
    $scope.loadMore = mainSvr.loadMore;
}]);

app.service('mainSvr', function () {
    // private
    var self = this;

    // public
    this.list = [];

    this.reload = function () {
        for (var i = 0; i < 5; i++) {
            self.list.push(i * 10);
        }
    };

    this.loadMore = function () {
        var listLength = self.list.length;
        for (var i = listLength; i < listLength + 5; i++) {
            self.list.push(i * 10);
        }
    }
});

My issue arises when I click on reload, as I want to clear and repopulate the list to display numbers from 0 to 40 again. How can I achieve this? I attempted:

this.reload = function () {
    self.list = [];
    for (var i = 0; i < 5; i++) {
        self.list.push(i * 10);
    }
};

However, it didn't work as expected. The list did get cleared and repopulated as per my code, but the UI didn't reflect these changes. Even after using the debugger and breakpoints, I couldn't figure out why the UI wasn't updating when I reset the list using self.list = []; Any insights on where I went wrong would be greatly appreciated.

Answer №1

To avoid overwriting the array reference with a new one, it is important to reset the existing array. One way to do this is as follows:

this.refresh = function () {
    self.data.length = 0;
    for (var i = 0; i < 5; i++) {
        self.data.push(i * 10);
    }
};

Angular's watchers digest cycle relies on strict object comparison. When you use self.data = [] to reset the list, you are essentially replacing the entire object reference, causing Angular to lose track of its previous state. On the other hand, using this.data.length = 0 allows you to clear the array without completely overwriting it - simply clearing it.

See in action: https://jsfiddle.net/fz2zgozx/2/

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 there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

Delay in changing the z-index of FloatingActionButton on hover

In my current issue, I am facing a problem where a div that is meant to always stay below a FloatingActionButton (FAB) ends up temporarily appearing above it when z-index values are changed. The scenario is such that upon clicking the FAB, an invisible ove ...

AngularJS form submission with Ajax requiring a double click to successfully submit the form

I need to perform the following activities on my HTML page: User inputs email and password for registration Form is sent to Controller when user clicks Submit Controller uses AJAX to create JSON request to RESTful Server and receives response from server ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

Having trouble getting Calendly Webhooks to function in a node.js environment with ngrok?

Hello everyone, this is my first time seeking help on Stack Overflow so please bear with me if there are any flaws in my question. I recently started using the Calendly Teams version and decided to implement the Webhooks feature on a Node.js web applicati ...

Three.js- I am having trouble with my shadow rendering, as lots of black lines are appearing everywhere instead of the shadows showing

Having recently delved into Three.js, I managed to add shadows to my model with the help of some knowledgeable individuals. However, upon the light hitting the model, numerous lines appear, causing me to question whether it's due to my poor modeling s ...

Angularfire social sign in with Facebook friends connections

When utilizing Facebook authentication with angularFire, I have encountered an issue where the "user_friends" object is not present in the Auth object that gets returned. Upon inspecting the code, it seems the ng-click directive used is as follows: "auth. ...

Is it possible to customize the notification message displayed after clicking the save button in a listview within ng-admin?

While working on the listview/creation view, I am attempting to incorporate a custom notification message instead of the default one (please see the screenshot) that appears when the user clicks the save button. Is there a way for me to include a custom n ...

Developing Authorization in AngularJS

Incorporating authorization into an AngularJS project is crucial. In my current project, which revolves around a social media concept, users with different roles may have varied access to view files. For instance, envision two distinct roles: customer and ...

Establish a connection to an already existing database using Mongoose

I've been exploring the inner workings of MongoDB lately. After setting up a local database, I created a collection with the following document: db.user.find().pretty() { "_id" : ObjectId("5a05844833a9b3552ce5cfec"), " ...

Choose specific dates from the data pickers based on the membership tiers and level of importance

I am seeking assistance in implementing a date selection functionality with different priority levels assigned to customers. Below is an explanation of the criteria: Customers with level 1 can choose dates from today up to 5 days in the future Cust ...

Tips for ensuring that the toJSON method in Sails.js waits for the find operation to complete before returning the object

When I try to run a find inside the toJSON function in the model, the object is returned before the find completes. How can I ensure that the return happens only after the find operation has completed? toJSON: function() { var obj = this.toObject(); Com ...

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

Error detected (unresolved promise): Invalid JSON format is causing an Unexpected token < at the beginning of data position (Application built with React/Redux)

I'm in the process of setting up user authentication using JWT. I've successfully created an API for this purpose. Now, my goal is to integrate this authentication API with my React/Redux App. When a user signs up, I trigger an action from my S ...

Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. Ho ...

What is the process of converting PUG to JSX?

I am currently attempting to integrate Pug code within a JS react application. While researching, I came across this plugin here, which can assist in converting the code. However, it seems to have an issue with handling the "." statements present in the c ...