AngularJS - Influence of Model on Controller leads to Model update

In my Angular application, I am facing an issue with data manipulation. The data is pulled from a model on app load and then modified in a controller's function. However, I only want this additional data to be used for that specific page without saving it back into the main model.

The structure of my model:

'use strict';
(function () {
    var PotsMod = function ($log, _) {
        return {
            pots: [
                {"comp" : "comp1"},
                {"comp" : "comp2"}
            ],
            getPots: function () {
                return this.pots;
            },
        };
    };
    angular
        .module('picksApp.models')
        .factory('PotsMod', PotsMod);
})();

And here is my controller:

(function () {
    function AdmCtrl($log, $routeParams, PotsMod) {
        var vm = this;
        vm.pots = PotsMod.getPots();
        vm.init = function() {
            // modify pot.competition values
            _.forEach(vm.pots, function(pot) {
                pot.comp = "test";
            });
            console.log(PotsMod.getPots());
        }
        vm.init();
    }
    angular
        .module('picksApp.controllers')
        .controller('AdmCtrl', AdmCtrl);
})();

My issue arises when trying to manage the data within the controller. Despite my attempts at debugging, the output seems contradictory and confusing.

Your assistance would be greatly appreciated in resolving this dilemma. Thank you.

Answer №1

Your controller is referencing the 'pots' object of the service, which means any changes made in the controller will affect the service's code as well.

To illustrate this concept, I have created a Plunker showcasing how angular.copy() can be used to create a deep copy of the service's 'pots', thereby decoupling your controller's model from the original data.

In order to implement this in your scenario, simply update your code to:

vm.pots = angular.copy(getPots());

Check out the Plunker for a live demo: http://plnkr.co/edit/abcd1234efg56789?p=preview

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 steps should be taken to resolve the nodemon error related to block-scoped declarations?

Below is the content of my package.json file: { "name": "pro-mern-stack", "version": "1.0.0", "description": "initial version", "main": "index.js", "scripts": { "start": "nodemon server.js server.js", "compile": "babel src --presets rea ...

Utilizing arrays to populate a line graph in Highcharts

I am struggling to figure out how to incorporate data from an array obtained from another function in my javascript file into my line graph. I want to confirm that this is feasible without switching to a different graphing package. Below is my current co ...

The Next.js 404 error page seems to be malfunctioning. Any ideas on what might be causing this issue?

Whenever I attempt to access a non-existent route, the home page loads without changing the URL. My expectation was to see a 404 error page. To handle this issue, I created a custom error page called pages/_error.js import Page404 from './404'; ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Updating an array within an object that is nested inside another array in MongoDB

I am faced with the task of modifying an array of objects within another array, and I am struggling to figure out how to achieve this. The position of the element in the array is stored in a variable rather than a string, which complicates things for me. I ...

Creating a multi-dimensional array in order to store multiple sets of data

To generate a multidimensional array similar to the example below: var serviceCoors = [ [50, 40], [50, 50], [50, 60], ]; We have elements with latitude and longitude data: <div data-latitude="10" data-longitude="20" clas ...

Looking for a way to extract information from two nested objects within an array by utilizing lodash, and then transferring it as a property to a react component

My react components require dynamic preloading of values from nested arrays within an array of data. import React, { useEffect } from "react"; export function loadComponent({ config, LayoutRenderer }) { const loadModules = (name) => q ...

jQuery Swiper slider

I am currently working with the Swiper jQuery slider for my project. As a beginner in programming (js / jquery), I am looking to run a specific function, involving some jquery code, whenever the first slide of the slider is active. It seems that this can ...

Hide the first child element

JavaScript $('dl #last div #product-tabs-content').not(":first-child").hide(); This testing code works perfectly, however... <dl class="last"><div class="product-collateral row-fluid"> <constructob> <ul class="pro ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

What part of the system generates sessions and cookies?

Is the following statement accurate? When developing a website, I utilize frontend javascript to create cookies and backend languages such as php or ruby to manage sessions? If this is correct, does the creation of sessions involve the browser generating ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Date discrepancy detected on AWS EBS server; however, it is operating seamlessly on the local environment

Whenever deployed on an AWS server, there seems to be a recurring miscalculation. Background: All dates stored in my MongoDB are in UTC format. I need them converted to IST before exporting them to Excel. While my code functions flawlessly on my local m ...

Exploring the process of obtaining a collection of JSON sub-items and using Angular's method for finding a match within an array

Question 1 In my program, I am receiving a JSON object called scope.tagSet, which has the structure shown below. { Tags : [ {"TagID" : "ID1" , "TagName" : "Name1"}, {"TagID" : "ID2" , "TagName" : "Name2"}, {"TagID" : "ID3 ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

What could be causing the image's width not to adjust when I apply "width: 8%;" in CSS?

Recently delving into the world of react, I set out to create a basic website featuring music notes (represented by simple images) that would change color upon hovering over them. While aware of the traditional :hover method, I decided to challenge myself ...

Tips for consistently obtaining the executed value of a getter in Mongoose?

In my mongoose schema, I have implemented a getter function for one of the properties as shown below: const User = new mongoose.Schema( { active: Boolean, email: {type: String, get: toLowerCase} } ) The toLowerCase function is def ...

How to Use Vanilla JavaScript to Fetch a JSON File, Convert the Data into an Array, and Iterate Through Each Object

Imagine having a JSON file called map.json: { "images":{ "background": ["images/mountains.png","images/sea.png"] } } The goal is for JavaScript to retrieve "images/mountains.png" from map.json and us ...

3D model suddenly transforming into darkness as it loads the mtl file

Whenever I load the MTL file, the entire model turns black. Despite setting the RGB parameters to 1 as suggested in this link, my issue remains unsolved. three.js mtl loader renders black Below is the code snippet associated with the problem: var scene = ...

Efficient page navigation bar that doesn't clutter the layout

I'm facing an issue with my navbar setup. I want it to stay at the top of the page without being sticky. However, the presence of the navbar is causing a scroll to appear on my page. This happens because: The navbar takes up space I sometimes use tri ...