3

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>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
anand patil
  • 507
  • 1
  • 9
  • 26

5 Answers5

3

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/

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
DoT
  • 89
  • 4
1

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>
artit91
  • 83
  • 7
0

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

sumair
  • 386
  • 3
  • 8
0

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>
Pranab Mitra
  • 401
  • 1
  • 4
  • 9
0

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>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121