AngularJS 1.6.1, TypeScript, UI Bootstrap Modal: How is my session storage data getting modified by the modal window?

Seeking assistance from the community. I am utilizing ngStorage to store some global variables:

//Global Controller
saveGlobalSettings = () => {
        this.$sessionStorage.QuoteTimes = this.quoteTimes;
        this.$sessionStorage.QuoteTypes = this.quoteTypes;
    };

Within another controller method, I am creating objects that incorporate some of these global variables as properties:

// Create Controller 
addChannel = (channel) => {            
        channel.QuotingChannelType = channel.QuotingChannelId;             
        console.log(this.$sessionStorage.QuoteTimes);
        channel.QuoteTypes = this.$sessionStorage.QuoteTypes;
        channel.QuoteTimes = this.$sessionStorage.QuoteTimes;
        if (!this.myChannels) { this.myChannels = []; }
        this.myChannels.push(channel);           
    };

Subsequently, I am using ng-repeat to present the objects in myChannels on the browser. Upon clicking an object, it is passed to the openDialog() method:

 openPreferencesDialog = (channel) => {
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };            
        this.$uibModal.open(options).result
            .then(updatedChannel => console.log(updatedChannel));               
    };

While the dialog opens correctly, any modifications made are updating the QuoteTimes and QuoteTypes arrays in $sessionStorage (as indicated by the console.log within addChannel). Consequently, each new object inherits the previous object's QuoteTimes and QuoteTypes. I am perplexed by this issue. Could it be related to a scope chain problem? Any insights on what might be going wrong?

UPDATE: By using JSON.parse(JSON.stringify(obj)); as shown below, I managed to achieve the desired behavior:

openPreferencesDialog = (obj, index) => {           
        var channel = JSON.parse(JSON.stringify(obj));
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };            
        this.$uibModal.open(options).result
            .then(updatedChannel =>
            {
                console.log(updatedChannel);
                this.$sessionStorage.myChannels[index].QuoteTimes = updatedChannel.QuoteTimes;
                this.$sessionStorage.myChannels[index].QuoteTypes = updatedChannel.QuoteTypes;
                console.log(this.$sessionStorage.myChannels)
            });               
    };

Can someone shed light on why this approach works?

Answer №1

When dealing with non-primitive types in a channel object, it is expected behavior for both the last edited channel object and $sessionstorage to have the same references to them in memory.

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

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Styling the first visible item in ngRepeat using Angular

I am working with a list that is generated using ngRepeat, which looks like this <ul class="list-group"> <li class="list-group-item" ng-repeat="data in tree | filter:key"> {{data.name}} </li> </ul> My goal is to ma ...

Guide to using express to render templates

Here is my current configuration: When I start the server and navigate to localhost, it directs me to home.ejs as specified in my front end routing: However, when I attempt to access localhost:3000/posts, the posts template does not get displayed on my i ...

Issue with AngularJs Autocomplete: this.source is not being recognized as a function

Below is the HTML code snippet for an autocomplete textbox feature: <body ng-controller="HomeController" ng-init="init()"> <div class="col-xs-4 search-bar-position" > <form role="search" > <div c ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

How can I run a TypeScript function within a JavaScript file?

I am working with a typescript file named file1.ts export function Hello(str: string) { console.log(str); } In addition, I have another file called index.js { require('./some.js'); } Furthermore, there is a script defined in the pack ...

After inputting the required parameters for the React onChange event, an unexpected error persists despite my efforts

I'm struggling with a bug in my React / typescript code. I have created a custom Input component that includes an 'onChange' property as described below: onChange?: (value?: string, event?: React.ChangeEvent<any>) => void; Here is ...

Use Angular to trigger a method when the Enter key is pressed, passing the current input text as a parameter

I need to extract the text from an input field and pass it to a method. Here is the code: index.component.html <input type="text" (keyup.enter)="sendData()" /> index.component.ts sendData() { console.log(The text from the input field); } Can ...

Issue encountered while attempting to utilize Semantic elements

I'm currently working on implementing a Transition component from Semantic UI React. I have the Semantic UI library installed and importing it as follows: import { Transition, } from "semantic-ui-react"; import 'semantic-ui-css/semantic.min ...

Alert of incompatible browser in application developed using create-react-app

After developing a web application using create-react-app, I encountered the issue of unsupported browsers such as IE10. Users with older browsers need to be notified to switch to a more up-to-date one for optimal performance. I find myself in a predicame ...

What could be causing the error message "Unable to access 'http' property of undefined" to appear in this validator?

Can someone help me with creating an asynchronous validator for a reactive form control that checks if a username already exists? Below is the code for the async validator: userdata.service.ts import { HttpClient } from '@angular/common/http'; i ...

Tips for testing watch expression in a directive using unit tests

I'm a beginner when it comes to unit testing and I couldn't find a solution to my issue anywhere online. That's why I decided to turn to the community for help. I have a directive that looks like this: angular.module('app') ...

Guide on utilizing $q for retrieving a promise from a $broadcast within angularJS

Currently, the controller code I've written is structured like so: $scope.spAPI.load(id).then(function(result){ var deferred = $q.defer(); if(result !== undefined){ deferred.resolve($rootScope.$broadcast("onSpLoaded", result)); } return de ...

Utilizing the identical modal for Add/Edit functionality within AngularJS

Recently, I started working with AngularJS and I am in the process of creating a simple project that involves creating, reading, updating, and deleting countries. The code is functioning correctly overall. However, I have encountered an issue regarding th ...

The type of a reference variable in a type definition of another variable

Can we reference the type of one variable (let's call it someVar) in TypeScript when declaring the type of another variable (anotherVar)? For example, instead of creating a separate type declaration for { complex: 'type' }, can we directly ...

Encountered an error: When trying to install styled-components using npm, there was an issue reading properties of null, specifically 'edgesOut'

C:\Users\user\Desktop\react_sce\test1> npm i styled-components Oops! An error occurred while trying to install styled-components. It seems like there's a problem reading properties of null (specifically 'edgesOut& ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

Tips for seamlessly incorporating a fresh ionic theme into your current ionic application

I am currently developing a project with Ionic v1 and Angular 1, using the basic Ionic UI. While browsing through the Ionic marketplace, I found several interesting themes. Can someone guide me on how to implement a new Ionic theme into my existing appli ...

Using TypeScript generics to efficiently differentiate nested objects within a parsed string

Consider the following type code: const shapes = { circle: { radius: 10 }, square: { area: 50 } } type ShapeType = typeof shapes type ShapeName = keyof ShapeType type ParsedShape<NAME extends ShapeName, PROPS extends Sh ...

Listening for changes made easy - AngularJS

Hey everyone, I'm experimenting with Angular JS and would love to hear some insights from all you experts out there :D What I'm currently working on is creating my own localization code. Yes, I know there are existing libraries available, but I ...