When transitioning to a different page, Angular is creating a duplicate of $scope

My webpage features a section where I showcase all the individuals stored in the database, referred to as the All Persons Page. Within this page, there are two primary options:

  • Add New Person
  • Delete Person (Any selected individual)

An issue arises when I navigate away from the page and return to the All Persons Page.

If I delete a person and then add a new one, the view will display both the newly added person and the deleted person.

In the controller, I populate an array with data retrieved from the DB.

$scope.persons_array = []

This data is displayed in the view using ng-repeat.

<div ng-repeat="(key, value) in persons_array)">

To add a person, a new ID is inserted into the array:

$scope.persons_array.push($scope.id[i])

To delete a person, the specified ID is removed from the array:

$scope.persons_array.splice(i,1);

Tests:

To investigate the problem, I implemented an setInterval function:

    setInterval(function(){
        console.log($scope.persons_array)
    }, 5000)

While on the All Persons Page with an existing person added, the output was:

[Object { id=667,  $$hashKey="object:71"}]

Upon navigating to another page and returning:

[Object { id=667,  $$hashKey="object:71"}] //original
[Object { id=667,  $$hashKey="object:220"}] //new

Adding a new person:

[Object { id=667,  $$hashKey="object:71"}] //original
[Object { id=667,  $$hashKey="object:220"}, Object { id=668,  $$hashKey="object:227"}] //new

Deleting the recently added person:

[Object { id=667,  $$hashKey="object:71"}] //original
[Object { id=667,  $$hashKey="object:220"}, Object { id=668,  $$hashKey="object:227"}] //new

Removing the person already present in the DB:

[] //original
[Object { id=667,  $$hashKey="object:220"}, Object { id=668,  $$hashKey="object:227"}] //new

Adding a new person once more:

[] //original
[Object { id=667,  $$hashKey="object:220"}, 
Object { id=668,  $$hashKey="object:227"}, 
Object { id=669,  $$hashKey="object:235"}] //new

It seems that upon navigating to another page, Angular somehow duplicates the $scope.persons_array and subsequently stops updating the original array.

Answer №1

Controllers in Angular do not get automatically released during route changes, so any intervals set within them continue running even after leaving the route. This means that the data used by that specific instance of the controller persists indefinitely.

To address this issue, Angular triggers a $destroy event when a controller is no longer associated with an active element. You can listen for this event within the controller to properly unbind ongoing functions like setInterval.

$scope.intervalID = setInterval(function(){
    console.log($scope.persons_array)
}, 5000);

$scope.on('$destroy', function() {
    clearInterval($scope.intervalID); 
    // Additionally, remove any unnecessary data
});

If you find yourself storing a lot of data on controller scope, consider using directives for instance-specific data or services for app-wide data storage instead of controllers. This approach not only addresses the issue mentioned above but also helps prevent scope leakage between directives sharing the same controller.

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

Dynamically adjust the gage value

Currently, I am working on a fitness application that involves showcasing BMI data using a gauge. However, I am struggling to figure out how to dynamically change the value of the gauge. In addition, when trying to implement the gauge script on button cl ...

Utilizing the power of THREE.ShaderLib.phong while integrating subsurface scattering within ThreeJS

My mesh utilizes a ShaderMaterial with THREE.ShaderLib.phong uniforms. I have successfully linked the map, bump, and specular maps textures. The code snippet below demonstrates this: defines = {}; defines["USE_MAP"] = ""; defines["USE_BUMPMAP"] = ""; defi ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

Encountering a Zone.js error when trying to load an Angular 7 app using ng serve, preventing the application from loading

Scenario: Yesterday, I decided to upgrade my Angular app from version 5.2.9 to 6 and thought it would be a good idea to go all the way to 7 while I was at it. It ended up taking the whole day and required numerous changes to multiple files, mostly due to R ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

Tips for managing a multi-page website with AngularJS

Currently, I am embarking on the development of an Android application using Cordova. To interact with the service end-point of a Drupal website, I have opted to utilize AngularJS for data fetching and manipulation. Initially, my attempt to incorporate ngR ...

Can a JavaScript function be used with images to operate across multiple elements?

How can I make a function work on multiple elements? let image = document.getElementById("opacityLink"); image.onmouseover = function() { image.style = "opacity:0.9"; }; image.onmouseout = function() { image.style = "opacity:1"; }; <div class=" ...

Separate the information into different sets in JavaScript when there are more than two elements

Upon extraction, I have obtained the following data: ╔════╦══════════════╦ ║ id ║ group_concat ║ ╠════╬══════════════╬ ║ 2 ║ a ║ ║ 3 ║ a,a ...

Button for Toggling Audio Play and Pause

Is it possible to create an SVG image that changes color slightly when hovered over, and when clicked toggles to another SVG image that can be switched back to the original by clicking again with the same hover effect? Additionally, when clicked, it should ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

Is the attribute of the label malfunctioning within an Angular directive?

As I delve into the world of angular directives, I have encountered success in many aspects. However, there is one minor issue that has been troubling me lately. Within my directive, I have set a for attribute to match the id of an input field. Strangely, ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

Tips for maintaining accessibility to data while concealing input information

Is it possible to access data submitted in a form even if the inputs were hidden by setting their display to none? If not, what approach should be taken to ensure that data can still be sent via form and accessed when the inputs are hidden? ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

Strategies for resolving the problem of null values from getParameter() being passed from AJAX to servlet

After reading numerous answers on Stack overflow, I have tried various solutions to fix this issue without success. My goal is to send a JavaScript variable to a servlet using AJAX within an else statement in JS. However, I keep receiving null in the alert ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: https://i.sstatic.net/lOI95.png Upon clicking a layer, my goal is to highlight and select it: https://i.sstatic.net/63Rx2.pn ...

Is there a way to ensure that the elements created by the select form are only generated once?

I have a JavaScript function that dynamically creates paragraph and input elements based on user selection in HTML. However, I am looking to optimize the code so that each element is only created once. Snippet of JavaScript code: function comFunction(sel ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...