What is causing the properties of my object to be overwritten?

I am facing an issue with my Angular code where I am trying to have multiple instances of the same Controller on a single web page. However, whenever a new instance is created, it replaces all other properties on the instance object instead of adding itself. This seems to be a JavaScript syntax problem rather than an Angular issue. Can anyone provide any guidance or advice?

angular.module('mean.root').controller('ContentA1Controller', ['$scope', '$location', 'Global', 'Data', '$timeout', '$interval', 'Clients', 'Modals', '$element', function ($scope, $location, Global, Data, $timeout, $interval, Clients, Modals, $element) {

            // Defaults
            $scope.instances = { A: {}, B: {}, C: {}, D: {}, E: {}, F: {} };

            // Methods
            $scope.createNewInstance = function() {
                var instance = $($element).closest('.content-container').attr('id');
                // Add ID to content
                $($element).find('.content').attr( "id", "contentA1instance"+instance );
                Data.priceByDay(function(prices){
                    // Load Chart Data
                    $scope.instances[instance].data = [1,2,3,4,5];
                    // Log Instance Object
                    console.log($scope.instances);

When I add one instance to the controller, everything works and I get this log:

$scope.instances = { A: { data: [1,2,3,4,5] }, B: {}, C: {}, D: {}, E: {}, F: {} }

However, when I add another instance by running createNewInstance() again, the log shows:

$scope.instances = { A: {}, B: { data: [1,2,3,4,5] }, C: {}, D: {}, E: {}, F: {} }

Answer №1

let selectedElement = $($selectedItem).closest('.wrapper-element').attr('id');
....
$scope.selectedInstances[selectedElement].values = [6,7,8,9,10];

This code snippet is retrieving the id of the closest .wrapper-element to the selected item where the script is executed on the webpage. It appears that the controller has been utilized twice, with one instance being closer to .wrapper-element#X and the other closer to .wrapper-element#Y. The functionality seems to be functioning as intended based on how it was designed, but there may be a discrepancy between what was intended and what was actually implemented.

Answer №2

In my opinion, it's best to assign a separate controller to each instance and store common data in $rootScope. Alternatively, you could consider using a single controller for the entire page and allowing each instance to manipulate individual map items.

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

In what way does AngularJS asynchronously navigate through the Angular template made up of HTML and AngularJS Directives?

While diving into the AngularJS book penned by Brad Green and Shyama Sheshadari, I stumbled upon the following insightful passage: The initial startup sequence unfolds as follows: 1. A user triggers a request for your application's first page. ...

The lifecycle methods in React consistently return the same props when updating the date

An interesting issue has emerged in a component that receives new props. The peculiar behavior involves the reception of an Object and a date object. Upon updating the object, in componentWillUpdate(nextProps, nextState), it is observed that nextProps.som ...

Use typescript to import an HTML template

My objective is to import my HTML template in a way that webpack can recognize and include them during the build process. (webpack -d) As advised in this GitHub thread, I should follow these steps: declare module '*.html' { const _: string; ...

Preserve the form's values after an onclick event to maintain the user's input in session storage

My website consists of a single page with an interface designed to showcase prediction results in {{ prediction_text }} from a flask backend. Users input values into a form that utilizes the app.py script to generate prediction outcomes. The issue I am fac ...

What is the reason for getAttribute not returning the name of the option field?

Here is the React code snippet that I'm working with: I need to fetch and store the key value on an option element when the select input is being changed. <select className={"select_1"} onChange={(event: React.ChangeEvent<HTMLSele ...

Using SVG in a Vue standalone script without the need for a build step is easy with the

When I attempt to utilize Vue as a standalone script in an HTML file, my inline svg icons are rendered as solid filled squares instead of their intended shapes. This issue persists when using both Vue 2 and Vue 3 as standalone scripts. Although there are ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Testing form submission in React with React Testing Library and checking if prop is called

Feel free to check out the issue in action using this codesandbox link: https://codesandbox.io/s/l5835jo1rm To illustrate, I've created a component that fetches a random image every time a button is clicked within the form: import { Button } from " ...

Corrupted image retrieved from a MySQL database stored as a Longblob data type

I've noticed many similar questions with different code solutions, but I've encountered a problem where changing the datatype to "Longblob" did not fix the issue. Even though my datatype is already Longblob, I still have broken images. My $pid i ...

Stopping the recursive function call in AngularJS

Utilizing the following function to retrieve users from a REST API, paginated by offset. Upon successful callback, the function recursively calls itself with a new offset to fetch the next set of users. Issue: When I change or exit the view, the FetchAtte ...

Struggling to eliminate HTML tags from a string containing the 'aspNetHidden' CSS class

I have a web user control that is being compiled into HTML. The issue I am facing is that the HTML is returning with view states enclosed in DIVs with a class of aspNetHidden. These DIVs are causing problems with my page's design, so I am attempting t ...

Warning: Fastclick alerting about an ignored touchstart cancellation

Having an issue with a double popup situation where the second popup contains selectable fields. Below is the code snippet I am using to display the second popup: $("#select1").click(function(e) { e.stopPropagation(); var tmplData = { string:[& ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Issue with Google chart: The visualization type gantt is invalid

I have attempted the solution provided here but unfortunately, the issue still persists. I modified useGstaticLoader: true in this However, upon checking the view, I received an error message stating: Invalid visualization type: gantt I would appreciate ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

Optimal strategy for creating a kiosk application that features dynamically changing views based on a timer

Currently, I am developing an app with 6 different views, each paired with its own controller. I am interested in implementing an automatic view switch after a certain number of seconds, looping back to the beginning once it reaches the end. In addition, ...

Establishing connection with SignalR JavaScript client

I'm unfamiliar with SignalR and I find myself feeling lost. My task is to establish a connection to a stream and retrieve certain data. The owner provided some guidance, but they are unsure how to accomplish this using JavaScript. They shared the fol ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

Modifying user-selected text styles with javascript

Currently, I am seeking a solution to modify the appearance of user-highlighted text on a webpage. My goal is for the selected text to retain its modified style even after it has been unhighlighted, similar to how a rich text editor functions. In attemptin ...