Angular and JS have differing opinions on how to determine if objects are equal

I am currently developing an application to showcase specific data using a grid and a data source.

Let me present the issue first and then elaborate on the situation.

$scope.onSelectRow = function (row, rowId) { 
                var a = row;
                var b = _.findWhere($scope.gridData.rows, {id: rowId});
                var c = a === b;
                console.log('Does JS think they are the same ? -> ' + c);
                console.log('Does Angular think they are the same ? -> ' + angular.equals(a, b));
                console.log('\nThe objects:');
                console.log(a);
                console.log(b);
                console.log('\nThe indexes:'); // what i really need
                console.log('Index of a:' + $scope.gridData.rows.indexOf(row));
                console.log('Index of b:' + $scope.gridData.rows.indexOf(b));
{

This code snippet aims to determine the index of the element. The element initially belonged to the $scope.gridData.rows array, which is displayed as a grid on the screen. The onSelectRow function triggers when a row is selected and receives 2 arguments:

  • row -> representing the entire table row directly linked to the $scope.gridData.rows array
  • rowId -> denoting the Id property of the row element (same as 'row' argument where rowId = row.id )

The output of these lines of code looks like this at one point:

However, upon updating and reloading the data, if someone clicks on a row again and the same logic repeats, the output changes to:

In the initial scenario, both Angular and JS recognize the objects as equal. Yet in the subsequent picture, JS fails to identify equality while Angular does... despite being essentially the same, as evident from the printed details and common origin.

Ultimately, my concern lies in obtaining the index of the selected element in the elements array without manually searching for it, since the correct object should ideally be returned by the table.

Any suggestions?

Answer №1

After carefully examining the documentation and taking into account @borja's response, it becomes apparent that angular.equals not only performs a '===' comparison but also evaluates other factors before arriving at a conclusion.

You can find more information at https://docs.angularjs.org/api/ng/function/angular.equals

Two objects or values are considered equivalent if at least one of the following is true:

  • Both objects or values pass === comparison.
  • Both objects or values are of the same type and all of their properties are > equal by comparing them with angular.equals.
  • Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  • Both values represent the same regular expression (In JavaScript, /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual representation matches).

Answer №2

To easily determine the index, you can simply pass it through the view using $index within the ng-repeat loop. The issue lies in the fact that a and b have different references, even though they have the same type, properties, and values. Angular considers them to be equal because of this, but the strict comparison operator === reveals that they are not truly equal.

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

Trouble with AngularJS Smart Table when dealing with live data streams

Currently, I am facing a scenario where I am utilizing angularJs smart table for filtering. Here is the HTML code: <section class="main" ng-init="listAllWorkOrderData()"> <table st-table="listWorkOrderResponse"> <thead> ...

React component utilizes Material UI to detect scrolling within a table

Currently, my table's body size is set to fixed dimensions in accordance with Material UI guidelines. I am looking to implement a functionality that allows me to dynamically load more rows as the user scrolls through the table. Can you recommend the ...

Creating random data in Vue is a fantastic way to enhance user

I'm attempting to retrieve a random quote from an API by generating a random index. However, when I click on the button associated with the index, I am not receiving a random quote as expected. Despite not encountering any obvious errors, the issue pe ...

Utilizing ng-pattern in Angular to detect leading zeroes in alphanumeric input fields

Are you wondering how to identify a leading zero in an alphanumeric field using ng-pattern in angular? <body ng-app> <h1>Regex test</h1> <form name="myForm"> <input name="myNumberField" ng-model="myNumber" ng-pa ...

Working with arrays and data to populate tables and cross tables using a single Eloquent Model in Vue and Laravel

There are three tables in the database: species, panel, and a cross table called species_panel. The relationship between them is that one panel can contain multiple species, so a one-to-many relationship is used. Data needs to be inserted into the panel ta ...

Issue with rendering second series in Highcharts Master Detail Chart

I'm currently facing an issue while setting up a Master Detail chart. Initially, both the master and detail graphs display line series and errorbar series. However, upon selecting a new range on the master chart, only the Line appears in the detail ch ...

Divide an array into two parts according to the property of objects using AngularJS

I have an array of objects derived from two different input fields on my form. Each object is identified by a unique id. The first field has id:1 and the second field has id:2. How can I efficiently split these objects into two separate arrays based on th ...

Embed a variable into an HTML element without affecting the inner HTML content

I am trying to inject a specific string into an HTML tag <td anyElement="{{myString}}" >some random text here </td> My desired interpretation is as follows: <td anyElement='Some string'>some random text here </td> Howe ...

Error: Unable to access undefined properties while trying to read 'add' value. Issue identified in the code related to "classlist.add" function

I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button. After researching on Stack Overflow, I stumbled upon a ...

JavaScript's async function has the capability to halt execution on its own accord

Presented here is a JavaScript async function designed to populate a sudoku board with numbers, essentially solving the puzzle. To enhance the user experience and showcase the recursion and backtracking algorithm in action, a sleeper function is utilized b ...

The ngMessages validation feature in AngularJS fails to remove error messages from the CSS styling

Can anyone help me figure out why I keep getting a red color underline error even though there is no actual error and validation is successful? https://i.sstatic.net/AESLl.png I created my own directive to validate passwords and I am using Angular materi ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

Having multiple instances of jQuery running concurrently on a single webpage

I am a novice when it comes to jQuery and I'm facing some issues with it. I have a basic slideshow and a weather plugin that I would like to incorporate, but strangely they both seem to malfunction when used together. <script src="js/jquery.js"> ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

Shifting Directive Logic to a Method within a Vue Component

I am currently working with a VueJS component that utilizes the style attribute in the following way: <section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: [& ...

How can I programmatically close the Date/Time Picker in Material UI Library?

Is there a way to programmatically close the Date/Time Picker in Material UI Library? ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...