AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below.

$scope.dirty = false;

init(data);

function init(data) {
    $scope.master = angular.copy(data.data);
    $scope.local = angular.copy($scope.master);
}

The 'local' object is used as the model for my form, along with submit and reset buttons. I monitor changes in the 'local' object like this:

  $scope.$watchCollection('local', function (newLocal, oldLocal) {
    $scope.dirty = !angular.equals(newLocal, $scope.master);
});

If the 'dirty' flag is true, I know that the data has been modified. However, due to AngularJS adding $$hasKey to $scope.local objects, the $scope.dirty variable always sets to true.

Is there any way to resolve this issue? I am new to AngularJS, so it may be a basic question but I'm struggling to find a solution.

Answer №1

If you want to ensure accuracy in your comparisons, one approach is to convert your object into a string using AngularJS's angular.toJson function:

function initialize(data) {
    // Save the JSON representation of data in $scope.master for future comparisons
    $scope.master = angular.toJson(data.data);
    $scope.local = angular.copy(data.data);  
}

$scope.$watchCollection('local', function (newData, oldData) {
    var jsonLocal = angular.toJson(newData); 
    $scope.status.dirty = !angular.equals(jsonLocal, $scope.master);
});

Answer №2

When sending data from PHP, it is important to note that PHP treats numbers and strings as separate data types. To ensure compatibility, I converted the number data to string format which resolved any issues. Additionally, working with AngularJS, I discovered that when using <form name='newForm>, AngularJS automatically creates a new scope named newForm. This allows for easy access to properties like $dirty, $pristine, $submitted, saving me the trouble of writing this logic myself.

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 trouble displaying the accurate model value in the alert

I have the following piece of code: $(document).ready(function () { var edit= @Model.Edit.ToString().ToLower(); if( edit !=true ) { $("#editWriteup").hide(); } var date= @Model.EndDate; alert(date); ...

"Encountering a 404 error when submitting a contact form in Angular JS

Looking to set up a contact form for sending emails with messages. Currently diving into Angular Express Node Check out the controller code below: 'use strict'; /** * @ngdoc function * @name exampleApp.controller:ContactUsCtrl * @descripti ...

Is incrementing x by 1 equivalent to x + 1?

I have a very basic angular application. It simply increases the value by 1 when clicked on using ng-click. Take a look at JSFiddle <div ng-app="app" ng-controller="ctrl"> <div ng-click="hello=hello+1">THIS WORKS ON CLICK: {{hello}}</d ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

The button vanishes upon being clicked

Is there a way to make a button disappear in Angular after it's been clicked? I've been searching for a solution for hours, but haven't found one that works. I need the button to vanish once the event occurs. Any suggestions on how to achie ...

What is the method to retrieve the return value from this ajax request?

Here's a code snippet: var information = { ObtainInfo : function() { var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/info/'+storage.get('apikey'); $.ajax({ url: url, su ...

Displaying or concealing dropdown menus based on a selected option

My goal is to have a drop-down menu in which selecting an option triggers the display of another drop-down menu. For example, if I have options like "Vancouver," "Singapore," and "New York," selecting Vancouver will reveal a second set of options, while ch ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Alter the URL and CSS upon clicking an element

Currently, I am faced with a challenge on my website where I have multiple pages that utilize PHP to include content and jQuery to toggle the display of said content by adjusting CSS properties. However, I am encountering difficulty in implementing this ...

Issues with npm @material-ui/core Button and TextField functionality causing errors and failures

I'm currently working on a React project and decided to incorporate the material-ui framework. After creating a component that includes a textfield and a button, I've encountered an issue where I can't interact with either of them as they s ...

JavaScript: Can you clarify the value of this variable using five sets of double quotations?

Could you please review the code snippet below for me? <script type="text/javascript"> function recentpostslist(json) { document.write('<ul class="recommended">'); var i; var j; for (i = 0; i < json.feed.entry.length; i++) { ...

Can Jquery be utilized to signal a language change?

I'm working on my portfolio website that will be available in two languages, Thai and English. I have successfully implemented language buttons for changing between the two languages. However, I am facing an issue with the language selection when nav ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Keep an ongoing execution of a node.js file by sending an HTTP request repeatedly

I am working on a project using node.js and express where I have a file named TCPServer.js that is responsible for polling a TCP/IP server. The goal is to send a single HTTP request to a database, retrieve the IP Address and port number, and then utilize t ...

Instructions on converting Dart to JavaScript for a non-web platform

I am interested in compiling Dart to JS for a non-web target, such as fermyon/js or node How can I compile Dart to JS for a non-web target? Update: I have been informed that it is possible, and although I couldn't find specific documentation, there ...

What are the steps for executing an API and entering data into it?

I have developed an API using NodeJS, ExpressJS and MongoDB to filter and sort school data based on location and fees. The main code snippet looks like this: const express = require('express'); const bodyparser = require('body-parser') ...

Unable to find 'react/lib/merge' module

I'm currently working on a React project and utilizing Babel and Webpack. Within one of my files, I have this require statement: var merge = require('react/lib/merge'); Unfortunately, I'm encountering the following error: ERROR in . ...

Could you explain the contrast among "yarn serve," "yarn start," and "yarn build"?

Although both "yarn serve" and "yarn start" can launch my Vue project, I'm unsure of the differences between them. I've heard that "yarn build" is for packaging, but why don't I use it at work? Usually, I just upload my code to git and let ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...