Retrieve the initial data of the AngularJS model upon button click

Previously, I was able to retrieve the initial values of the model using this.model.changed or this.model._previousAttributes in BackboneJS.

Now, I am looking to achieve the same functionality in AngularJS, where I can track all changes made to the model through text fields and checkboxes, not just a single text field like with ng-change.

I have attempted to incorporate this within a form div without success.

I also experimented with:

 $scope.policyL = savingsDraft.fromServer();
    $scope.$watch('policyL', function (oldV, newV) {
 });

Unfortunately, this approach did not yield the desired result either.

Here is an example snippet from my view code:

form(role='form', ng-change='changed (policy, newP)' novalidate)
  .row
    .col-sm-4.form-group
      label.control-label Taux de rendement
      input.form-control(type='number',
        min=0,
        max=1,
        ng-model='policy.admin.depEarnRate')
    .col-sm-4.form-group
      label.control-label Frais de contrat
      input.form-control(type='number',
        min=0,
        ng-model='policy.admin.feesIni')

And in my controller:

$scope.accept = function () {
     $scope.change = function();
};

PS: My ultimate goal is to retrieve the original model data after clicking on the accept button.

Answer №1

One approach would be to create a duplicate when the controller is initialized. When the $watch event is triggered, simply check if the current model differs from the duplicate. If they are not the same, use the value from the duplicate.

Answer №2

It is always a good idea to preserve the original data when working with forms so that it can be easily reset if necessary.

$scope.master = dataModel;
$scope.dataModel = angular.copy($scope.master);

$scope.reset = function () {
    $scope.dataModel = angular.copy($scope.master);
    $scope.yourForm.$setPristine();
};

If you only want to track the changes made from the original data, you can customize Backbone's changedAttributes method for this specific purpose.

var changedAttributes = function(master, diff) {
    if (!diff) return false;
    var changed = {};
    for (var attr in diff) {
        var val = diff[attr];
        if (!_.isEqual(master[attr], val)) changed[attr] = val;
    }
    return _.size(changed) ? changed : false;
},

To implement this:

var changes = changedAttributes($scope.master, $scope.dataModel);
if (changes) console.log("dataModel has diverged from master");

To incorporate underscore into an Angular app, angular-underscore provides a reliable solution.

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

Having issues with the functionality of my radio button in AngularJS

As I delve into Angular and experiment with some code, I am focusing on implementing the following functionality: 1. Depending on the user's preference for adding additional details, they can choose between 'yes' or 'no' using radi ...

What is the best way to empty an array within the state of a React component using JSX?

I need assistance with a React and JSX project where I am creating input fields that can be removed by clicking a button. Currently, I have an empty array stored in the state of the Page component. This array is updated using the addItems function. Howev ...

Experiencing difficulties when trying to input text into a React text field

For a university assignment, I am using the create-react-app to build a website. I am facing issues with the input text field as I cannot type into it when clicked. There are no error messages indicating what could be wrong. The objective is for users to ...

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: https://i.sstatic.net/fr7oJ.png My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: https://i.sstatic.net/uhkp9.png To create th ...

When the browser window is resized to mobile view, a div is overlapped by an image

I've encountered an issue with the image size and position when resizing to mobile view in the browser. .extension { display: table; padding: 50px 0px 50px; width: 100%; height: auto; color: #fff; background-color: #558C89; ...

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

Querying Denormalized Data in AngularFire 0.82: Best Practices and Strategies

I have a question that is related to querying denormalized data with AngularFire. I am looking for a solution specifically using AngularFire (current version 0.82). Here is an example of the data structure I am working with: { "users": { "user1": { ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Received an error while attempting an AJAX GET request to a distinct server hosting a WebAPI

This is my first time encountering an issue with an Ajax request in client-side code. I'm hoping that there's a simple mistake in my code that I'm just overlooking. Just to give some background, when I manually access the URL mentioned below ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

Is it possible to enable a button as soon as input is entered?

I'm encountering a minor issue with my button's functionality. I am attempting to have the button enabled as soon as text input is entered into the text field, but currently it only becomes enabled after the focus has changed from the text field. ...

Reload a tab on an ajax-enabled webpage

I am currently facing an issue with refreshing a tab instead of the entire page using Ajax. The specific tab in question involves deleting credit cards. When I select the credit card I want to delete and confirm, I use "window.location.reload();" to refres ...

Tips for passing an additional parameter to a function within the map method in JavaScript

Is there a way to pass an additional parameter to the aggregationFunction in JavaScript when using dataArray.map(self.aggregationFunction)? I attempted using .bind(extra parameter) but it didn't yield the desired result. Any advice would be appreciate ...

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...

Tips for adjusting the position of an infowindow in ArcGIS

I have implemented the use of infowindow in arcgis to display certain information. https://i.sstatic.net/Dnpas.jpg Currently, the infowindow is appearing directly over my icon. Is there a way to adjust its position if it covers the icon? ...

Issues with applying styles to custom components in styled-components

I attempted to customize the inner elements of react-id-swiper using the code below: import Swiper from 'react-id-swiper'; import styled from 'styled-components'; const MySwiper = ({ className, children }) => ( <Swip ...