Please help a newb out. I'm using ngStorage to store some global variables:
//Global Controller
saveGlobalSettings = () => {
this.$sessionStorage.QuoteTimes = this.quoteTimes;
this.$sessionStorage.QuoteTypes = this.quoteTypes;
};
I'm using another method in another controller to create objects that use some of the 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);
};
I'm then using ng-repeat to display the objects in myChannels in the browser. When clicked, I'm passing the object to an 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));
};
The dialog opens as expected, but when I make changes, it is updating the QuoteTimes and QuoteTypes arrays in $sessionStorage (seen from the console.log in addChannel). So each new object created has the QuoteTimes and QuoteTypes of the last object I edited. I am completely stumped. My best guess is it's some kind of scope chain problem? Any idea what I'm doing wrong?
UPDATE: I was able to get it working as expected by using JSON.parse(JSON.stringify(obj)); as follows:
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 anyone explain why this works?
If quote... members of channel object are not primitive type it's normal behaviour. Because they are reference type that both last edited channel object and $sessionstorage have same references to them in memory.