Angular: The Process of Completely Updating a Model Object

Within my application, there is an object named eventData which acts as a singleton and is injected into multiple controllers through a resolve function.

This eventData contains various sets of data such as drop down list values along with the main model. In simple terms, its structure looks like this:

eventData.DropDownListValues1
eventData.DropDownListValues2
eventData.MyModel

In each controller, the implementation goes as follows:

angular.module('myWebApp.controllers').
    controller('MyCtrl', function ($scope, eventData, coreAPIservice, ViewMatrixService, UtilityService) {

        $scope.myModel = eventData.MyModel;
        $scope.dropDownListValues1 = eventData.DropDownListValues1;
});

The views are represented like this:

<select class="form-control input-sm"
        ng-model="myModel.Item"
        ng-options="myItem as myItem.ItemName for myItem in dropDownList1 track by myItem.ItemId">
    <option value="" selected disabled hidden>Select Item...</option>
</select>

When the post request to the webservice returns the updated model with new database-generated IDs, attempting to reassign eventData.MyModel does not trigger updates in all referencing controllers.

coreAPIservice.UpdateEvent(eventData.MyModel).success(function (response) {
    eventData.MyModel = response;
});

Typically, changes to a specific property within the model trigger immediate updates across all associated controllers/views such as:

$scope.myModel.myProperty1 = "abcdefg";

However, replacing the entire MyModel object seems to break references and hence, fails to update the views.

To address this issue, two potential solutions have been considered - either fetching the data again after a post request or updating each property individually.

Re-fetching data feels redundant and slows down the process since the updated model is already available post-request. On the other hand, individually updating over 1000 properties on MyModel is time-consuming and may affect performance negatively.

Answer №1

Modify the constructor code of your controller in the following way:

$scope.eventData= eventData;
Object.defineProperty($scope, "myModel", { get: function () { return $scope.eventData.MyModel; } });
Object.defineProperty($scope, "dropDownListValues1", { get: function () { return $scope.eventData.DropDownListValues1; } });

This code snippet registers myModel as a property (not a field) on the $scope object. It ensures that the property always retrieves the MyModel object from the eventData whenever it is referenced. By implementing this change, you can maintain your existing HTML structure without any modifications. Additionally, it allows you to update the entire model on your EventData instance without the need to push events through. While your controller will hold a reference to the EventData, you only need to access it within the created getter property.

Please verify the JavaScript syntax provided, which was sourced from here

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

Can you explain the functions of this "malicious" JavaScript code?

I came across this piece of code on a website that labeled it as "malicious" javascript. Given my limited knowledge of javascript and the potential risks involved in trying out the code on my own site, I was hoping someone here might be able to shed some l ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

How can a JavaScript function be triggered by Flask without relying on any requests from the client-side?

I'm in the process of setting up a GUI server using Flask. The challenge I'm facing is integrating an API that triggers a function whenever there's a change in a specific Sqlite3 database. My goal is to dynamically update a table on the HTML ...

Unable to retrieve or remove cookie sent from Express on client side

My Express server is sending a cookie to the client that is not httpOnly. Despite this, the client is unable to access the cookie through document.cookie or see it in the Application tab on chrome dev tools. Interestingly, I am able to view the cookie in C ...

Is there a way to retrieve the HTML code of a DOM element created through JavaScript?

I am currently using java script to generate an svg object within my html document. The code looks something like this: mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); myPath = document.createElementNS("http://www.w3.org/2000/svg", ...

Issue encountered when configuring multiple ui-views in index.html - no output on display

I am currently working on implementing a feature similar to what is demonstrated in the Multi-Named-Views wiki page of the ui-router. The example code snippet I am referring to is as follows: $stateProvider .state('report', { views: { ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

The outcomes of JSON.stringify and JSON.parse can vary

I am facing an issue with using JSON.stringify to create a JSON string from an Object. After saving the string into a file, I attempt to read the file and use JSON.parse to retrieve the object again. However, it seems that the process is not working as exp ...

There seems to be a syntax error lurking within npm.js, and for some reason npm insists on utilizing version 10.19.0 of Node.js despite my attempts to update it. The reason behind this behavior

Apologies if this question seems silly, but just a couple of days ago my code was running perfectly fine. Then today when I tried to load it, I encountered all sorts of errors. I am fairly new to node and npm, so I suspect it could be related to version ma ...

Running an Angular 2 application locally without using Node? Here's how you can do

After completing a tutorial on creating a movie finder app using Angular 2, I found that the project could only be viewed by running 'npm start' in command line. Is there a way to allow others to view my project locally on their machines even if ...

Iterate over asynchronous calls

I am currently working with a code snippet that loops through an Object: for(var x in block){ sendTextMessage(block[x].text, sender, function(callback){ //increment for? }) } During each iteration, I need to make a request (send a Faceboo ...

Error: The property 'length' cannot be read from an undefined parent causing Uncaught TypeError

Hey there, take a look at this cool stuff http://jsfiddle.net/J9Tza/ <form class="validation"> <div> <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" pattern=".{3,200}" title="3 to 200 characters" r ...

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

Include an additional capital letter at the beginning of each new item in ng-repeat

My array is organized as follows: [aa,ab,ba,bb] My desired rendering is: A aa ab B ba bb What changes can I make to this loop to achieve this? <div ng-repeat="item in array" > {{item}} <br> </div> ...

What is the best way to fill an array within an object using React Hooks?

I am encountering an issue with an object that includes an array. Here is the code snippet in question: const [data, setData] = useState({ jobs: [] }); Currently, I am retrieving data from an API and need to append this fetched information to the jobs arr ...

What is the process for making local dynamoDB queries with dynamoose?

In order to avoid constantly connecting to Amazon Web Services as a developer, I decided to install DynamoDB on my local computer following the guidelines provided in the AWS Docs. My backend is built using node.js. For modeling Amazon's DynamoDB in ...

Having trouble retrieving AJAX data [PHP]

When a form on my homepage (index.php) is submitted, it opens a randomly generated URL in a new tab. This random URL runs a script named run.php. <form action="/run.php" method="POST" target="_blank"> <input type="hidden" id="idgen" name="idg ...

Utilizing visual representations for "symbol" within eCharts4r

I have been exploring the use of the "image" option for the symbol parameter in a tree chart with eCharts4r. Despite trying multiple methods, I am struggling to assign a unique image to each node in the tree instead of using a universal one. However, my a ...