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

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Retrieve a Play Scala variable in the $scope of an AngularJS application

After trying various methods recommended on StackOverflow, I am still struggling to retrieve a Play Scala variable within my Javascript $scope. The line of initialization in an HTML file is as follows: @(playVariable: String)(implicit request: play.api.mv ...

Error: The createContext function is designed for use only in Client Components. To enable it, include the "use client" directive at the beginning of the file

After creating a fresh Next.js application with the app folder, I proceeded to integrate Materiel UI following the example provided in the documentation. However, I encountered an error: TypeError: createContext only works in Client Components. Add the & ...

Interacting with a C# Web Service Using JQuery

I've set up a JSON web service in C# and I'm working on creating a custom HTML page to interact with it. http://localhost:25524/DBService.svc/json/db=TestDB/query=none When I input this URL into my browser, I expect to receive JSON formatted da ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

"Adding properties to objects in a map: a step-by-step guide

During my attempt to add a property within a map loop, I noticed that the update appeared to occur on a duplicate rather than the original object. MY_ARRAY.map(function(d){ d.size = DO_SOMETHING }); ...

Move and place, editing tools

Is it possible to create a drag-and-drop editor similar to the one found in the form editor on wufoo.com? ...

Surprising outcome arising from simultaneous execution of numerous asynchronous operations on every individual object within an array

I'm fairly new to working with Node.js and I'm still trying to grasp the concept of callbacks and the asynchronous nature of Node.js. However, I've encountered a problem that I can't seem to solve. I've already searched extensively ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

Having trouble retrieving accurate JSON data from an excel workbook

Currently, I am utilizing the npm module xlsx for the purpose of writing and reading JSON data. My goal is to take this JSON data and write it into an Excel file: { "name": "John", "class": 1, "address" : [ { "street": "12th Cross", "city": "London" }, { ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

The outcome does not display default selected checkboxes

I am facing an issue with default checked items. The default checkbox is functioning properly, but when I click a button to display all checked items, the default checks are not being shown (they appear as unchecked). However, if I uncheck and then check t ...

Utilizing Vue with Nuxt.js: A Guide to Parsing POST Request Parameters from External Sources

I am currently facing an issue with accessing the POST request parameters from an external form in my nuxt app. Despite trying to utilize the "asyncData" method, I continue to receive an "undefined" value when attempting to access the submitted parameter t ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

What is the best way to define file paths in a webpage to ensure that the same file works seamlessly on both server and

Currently, I am working on developing a website locally with the intention of later transferring it via FTP to my server. In my index.php file, there is a line that reads: <?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");?&g ...

The jQuery UI Tab is failing to scroll within its container

Scenario : I am facing an issue with a scrollable container in IE8. The containing div is supposed to be scrollable and it holds my jquery UI tab div. Issue: While scrolling the container in IE8, other content within it also scrolls, but the jQuery UI t ...