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

What is the best method for connecting an Angular 2 application with an existing Angular JS app?

I recently created an application using Angular 2 and now I am looking to combine it with an Angular JS app. ...

Accessing information from a json response using an ajax request

Currently, I am making an ajax call to fetch the longitude and latitude based on a pin code. Here is how I approached it: $(document).ready(function () { $.ajax({ type: "GET", url: "http://maps.googleapis.com/ma ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

Problems arise when JQuery fails to function properly alongside ajax page loading

While utilizing ajax to load the page, I encountered an issue where the jQuery on the loaded page template was not functioning until the page was manually refreshed. The ready function being used is: jQuery(document).ready(function() { jQuery(' ...

Managing Unauthorized Responses in Angular

I have a simple API with an authorization point When I make a request to the API, I receive a 401 error if the token is invalid (the token expires after five minutes). I am aware that I can intercept the 401 error by using: app.factory("HttpErrorInterce ...

The functionality of the Angular Bootstrap UI accordion is not meeting the desired expectations

I am currently utilizing the accordion feature from Angular Bootstrap UI. By default, the first accordion is expanded. When a user adds a new accordion, the first accordion should automatically collapse, and the newly added accordion should expand. Clickin ...

Investigating TLS client connections with node.js for troubleshooting purposes

I am currently facing an issue while setting up a client connection to a server using node.js and TLS. My query revolves around how I can gather more information regarding the reason behind the connection failure. It would be great if there is a way to ob ...

Develop a client-side API utilizing various libraries

After completing the server side of an API that delivers HTML via JSON using REST through CodeIgniter, I am now exploring how to create a client-side API with JavaScript. The goal is to retrieve data from the server through the API, display it in the DOM, ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...

combine two 2D arrays in JavaScript

I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In oth ...

`In Internet Explorer, dropdowns in AngularJS ng-repeat are not displaying properly.`

I am facing an issue with rendering a list of components with dropdown controls in IE10. Even though it works perfectly fine in Chrome and Firefox, the dropdowns don't display correctly in IE10. When I have the following code: <select ng-model="se ...

The "<p> angular" text is separated by commas

I am still learning Angular and facing a simple challenge. I want to convert JSON data like this: [ {'name': 'Anna'}, {'name': 'Ben'}, {'name': 'Chris'}, ] Into this format: <p&g ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...