2

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>
5
  • you want to do it in controller or template? Commented May 14, 2016 at 15:33
  • @sumair - In template(the html file) Commented May 14, 2016 at 15:34
  • Out of interest why aren't you using an object? Commented May 14, 2016 at 15:36
  • @SmokeyPHP - I could use an object too. But curious to know how to do it for an array? BTW, is it possible for an object? Commented May 14, 2016 at 15:37
  • Please find the similar post stackoverflow.com/questions/19544904/… Commented May 14, 2016 at 15:56

5 Answers 5

4

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/

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

0

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

Comments

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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.