anand patil
anand patil

Reputation: 507

AngularJS - ng-repeat over array with string index

How to ng-repeat over array with string index? Please see below snippet of the code-

Below code is in a controller.

$scope.days = ["mon", "tue", "wed" .... "sun"];
$scope.arr = [];
$scope.arr["mon"] = ["apple","orange"];
$scope.arr["tue"] = ["blue","swish"];
.
.
.
$scope.arr["sun"] = ["pineapple","myfruit","carrot"];

Question - How to ng-repeat like something below, is it possible?

<div ng-repeat="day in days">{{day}}
    <span ng-repeat="item in arr(day)">{{item}}</span> 
    <-- Something like "arr(day)", can it be done in angular -->
</div>

Upvotes: 2

Views: 16460

Answers (5)

DoT
DoT

Reputation: 109

You can just use normal syntax for item in an array. Please refer my fiddle

<div ng-app='app' ng-controller='default' ng-init='init()'>
  <div ng-repeat='day in days'>
    <strong>{{day}}</strong><br/>
    <span ng-repeat="item in arr[day]">{{item}} </span> 
  </div>
</div>

https://jsfiddle.net/DoTH/evcv4tu5/3/

Upvotes: 4

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

Yes, this is absolutely possible. See a working example below:

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {
  $scope.days = ["mon", "tue", "wed", "sun"];
  $scope.arr = [];
  $scope.arr["mon"] = ["apple", "orange"];
  $scope.arr["tue"] = ["blue", "swish"];
  $scope.arr["sun"] = ["pineapple", "myfruit", "carrot"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <ol>
    <li ng-repeat="day in days">
      <strong>{{day}}</strong>
      <ol>
        <li ng-repeat="item in arr[day]">{{item}}</li>
      </ol>
    </li>
  </ol>
</div>

Upvotes: 0

Pranab Mitra
Pranab Mitra

Reputation: 389

You can print the item number too.

<div ng-repeat="day in days">
    {{day}}
    <div ng-repeat="(key, value) in arr[day]">Item #{{key + 1}}: {{value}}
    </div>
    <br />
</div>

Upvotes: 0

sumair
sumair

Reputation: 386

You can use it like this ng-repeat="item in arr[day]"

Upvotes: 0

user3339197
user3339197

Reputation:

Use square brackets to access object/array fields/elements.

<div ng-repeat="day in days">{{day}}
    <span ng-repeat="item in arr[day]">{{item}}</span>
</div>

Upvotes: 1

Related Questions