Angular JS: Displaying the first element from an array of arrays using ng-repeat

Posted by


In AngularJS, the ng-repeat directive is used to iterate over items in an array or object and generate HTML elements based on those items. In this tutorial, we will focus on how to use ng-repeat to target the first element from an array of arrays.

Let’s say we have an array of arrays like this:

$scope.arrayOfArrays = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

Our goal is to use ng-repeat to target only the first element from each sub-array and display it in the HTML. Here’s how we can achieve this:

  1. In your HTML file, create a div element with an ng-app and ng-controller directive to initialize your AngularJS application and controller. For example:
<div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="arr in arrayOfArrays">
            {{arr[0]}}
        </li>
    </ul>
</div>
  1. In your AngularJS script, define your module and controller. Inside the controller, define your array of arrays:
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.arrayOfArrays = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ];
});

In the HTML code above, we are using ng-repeat to iterate over each sub-array in arrayOfArrays. By using the expression {{arr[0]}}, we are accessing the first element of each sub-array and displaying it as a list item.

When you run this code, you will see a list with the first element from each sub-array displayed:

  • 1
  • 4
  • 7

This is a simple example of how ng-repeat can be used to target specific elements within an array of arrays. You can modify the HTML and JavaScript code to suit your specific needs and display the data in a different format.

Overall, ng-repeat is a powerful directive in AngularJS that allows you to easily iterate over arrays and objects and generate dynamic content in your web application. It simplifies the process of working with data and displaying it in the user interface.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x