How do you access objects in HTML and JavaScript using different notations - "." in HTML and "[]" in JavaScript?

I understand the functionality, but I'm curious about the reasoning behind using "." in HTML to access an object and "[]" in JavaScript. Here is the code snippet for reference. Can anyone shed some light on this? Thank you.

<div ng-app="testApp" ng-controller="testCtrl">
    <div ng-repeat="detail in details">
        <span>{{detail.numbers.length}}</span> <!-- Output: 1, 2, 3 -->
        <!-- Won't work: <span>{{details[detail].numbers.length}}</span> -->
    </div>
</div>

angular.module("testApp", []).controller("testCtrl", function ($scope) {
    $scope.details = [{"numbers": [1]}, {"numbers": [2, 2]}, {"numbers": [3, 3, 3]}];
    for (var detail in $scope.details) {
        console.log($scope.details[detail].numbers.length); //Output: 1, 2, 3
        //Won't work: console.log(detail.numbers.length);
    }
})

JSFiddle: https://jsfiddle.net/ealonwang/d5yL8ydk/18/.

To view the results of console.log(), right click and inspect the page.

Answer №1

When working with an array of objects in your example data, there is a discrepancy between how Angular and JavaScript handle array iteration.

Angular iterates through arrays of objects by returning the object for each iteration, while the in operator in JavaScript returns the array index for each iteration. You can learn more about this at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

In HTML, you have the option to use an alternate syntax for ng-repeat that will provide the index for each iteration, like so:

"ng-repeat = (index, detail) in details"
. Alternatively, you can leverage the automatically generated $index parameter if the array is static.

Within JavaScript, Angular offers an iterator function similar to ng-repeat, which will return the object for each iteration. Here's an example:

angular.forEach($scope.details, function(detail){
  console.log(detail.numbers.length);
});

For more information on Angular's iterator function, visit: https://docs.angularjs.org/api/ng/function/angular.forEach

Answer №2

When utilizing square brackets, they are commonly paired with the index of an item in an array. If you need to access items by their index, utilize this ng-repeat version.

<div ng-app="testApp" ng-controller="testCtrl">
    <div ng-repeat="(k,detail) in details">
        <span>{{detail.numbers.length}}</span> 
        <span>{{details[k].numbers.length}}</span> 
    </div>
</div>

The variable k will represent the key, which corresponds to the index of each item returned by the ng-repeat directive.

During iteration with a for loop, the value assigned during initialization/variable expression will be the index and not the array item. To access each item within a loop, consider using the angular.forEach method. This method will pass each array item as an argument to the callback function.

$scope.details = [{"numbers": [1]}, {"numbers": [2, 2]}, {"numbers": [3, 3, 3]}];

angular.forEach($scope.details, function(detail, key) {
     console.log(detail.numbers.length);
     // or 
     console.log($scope.details[key].numbers.length);
});

View a live example 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

Generating replicated elements at varying positions

After discovering that my previous question, which can be found here, is currently not feasible due to limitations with html2canvas only taking 'snapshots', I have chosen to approach the problem differently. The new approach involves making an o ...

Issue with Material-UI: Unforeseen TypeError arises while toggling between two Drawer elements

Note: I am utilizing material-ui 3.3.0 My goal is to have two <Drawer> components displayed on a page, with one sliding in from the left and the other from the right. In an <AppBar>, there are two <Button> components that toggle the visi ...

Dynamically loading iframes with JQuery

I have implemented a jQuery script to load another URL after a successful AJAX request. $(document).ready(function() { var $loaded = $("#siteloader").data('loaded'); if($loaded == false){ $("#siteloader").load(function (){ ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

AngularJS ng-repeat filtering by date is there any solution?

I have a ng-repeat loop with dates in the format below: <small>Added: <strong>{{format(contents.completeddate)}}</strong></small> I am using a datepicker plugin that provides me with 2 objects - a start date and an end date. For ...

Trouble with callback execution during async foreach loop when using collection.save() in Node.js

In my quest to store records in a mongoDB collection while in an async foreach loop, I encountered an issue where the code seems to be skipping the save part altogether. Here is the relevant snippet: async.forEach(data, function(item, callback) { va ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

Utilize the image button to transfer a picture from your desktop

I have created a table using HTML. The first cell of the table (1,1) contains an image that I want to function as a button. When the image is clicked, I would like to be able to select a photo from my computer and add it to the next available cell in the t ...

Drawing on an image in Angular2 Ionic2: Step-by-step guide

I have experience drawing in Angular1 Ionic1. In my HTML: <img ng-src="{{image}}" style="width: 100%"> <canvas id="tempCanvas"></canvas> In my controller var startimg="img/face.jpg"; $scope.image=startimg; var canvas = document.getEl ...

My AngularJS integrated with Spring MVC is failing to render the desired page

Hello everyone, I'm fairly new to AngularJS and Spring MVC. I've managed to set up a basic application, but unfortunately, when I try to load it, nothing appears on the screen. The console shows a 404 error. I've double-checked everything, b ...

Utilize three.js to animate a virtual reality humanoid model mapped to skeleton coordinates

As someone who is new to three.js and animation, I find myself struggling with concepts like rotation angles, VRM interactions, and humanoid animations. Despite my confusion, I will do my best to articulate my question below. I have a series of frames tha ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

Twitter posting unsuccessful: Issue encountered - Your current access is restricted to certain Twitter API v2 endpoints along with limited v1.1 endpoints like media post and oauth

My JavaScript app uses NPM Twit to post on Twitter. Suddenly, my bot stopped working with no explanation. It turns out that Twitter required me to switch to their new free tier and I had to delete all content from my Twitter Dev account and recreate my pro ...

What are the different HTTP Methods supported by AJAX?

Considering that HTTP supports a variety of methods such as GET, PUT, POST, DELETE (and others like PATCH, HEAD, OPTIONS, etc.), I am pondering over which of these methods an AJAX request typically utilizes. Is there an option to specify which method we ...

Make sure to include a space before each character when entering text in TinyMCE

I am interested in creating a MS-Word-like system for managing non-breaking spaces before certain characters: My goal is to automatically insert a non-breaking space before characters like ?, !, :, etc. while typing (or replace a normal space with a non-b ...

What are some effective approaches to consider when developing AngularJS directives?

How can one ensure best practices are followed when creating angularJS directives? Some key points to consider: The optimal size of the link function Best practices for what to do and what not to do in the link function The proper usage of scope.$apply ...

Tips for adjusting the dimensions of material table within a react application

Could someone please provide guidance on adjusting the size of a table made with material table? I am currently working in React and the following code is not yielding the desired outcome. I even attempted to use 'react-virtualized-auto-sizer' wi ...

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

What is the method for incorporating an extra event handler in jQuery or regular JavaScript?

In my object, I have a custom onShow() function that is called when the object is displayed. I am able to override this function by reassigning it. o.onShow = function() { // do something }; However, overriding the function removes the previous version. ...

Creating a div resizing function using only JavaScript is a fun and useful project to tackle

Seeking help to create a div resizer using only pure JavaScript as jQuery is restricted. The current functionality works, but breaks when the position of the slider-div is not set to absolute. Any solutions to fix this issue would be greatly appreciated. ...