Jean Corzo
Jean Corzo

Reputation: 55

ng-repeat on subarray not working?

I have this code:

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [{
    val: 'bleh1',
    subval: [{
      attr1: 1,
      attr2: 2
    },{
      attr1:3,
      attr2:4
    }]
  }, {
    val: 'bleh2',
    subval: [{
      attr1: 1,
      attr2: 2
    },{
      attr1:3,
      attr2:4
    }]
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="angularjs-starter">
  
  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script>
      document.write('<base href="' + document.location + '" />');
    </script>
    <script src="app.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
    <div ng-repeat="item in items.subval">
      <div>{{item.attr1}}</div>
      <div>{{item.attr2}}</div>
  </div>
  </body>

</html>

I've been trying to figure out why the ng-repeat is not working but i have not been able to solve it. I followeb the AngularJS course on CodeSchool and also went through the AngularJS tutorial tho i can't find the error in my code. I've been looking around here as well and could not find a solution either. Can you guys point me what i should look for or what is the mistake i have please?

Upvotes: 0

Views: 1547

Answers (1)

JLRishe
JLRishe

Reputation: 101652

items does not have a property called subval, since items is an array. I think the thing to do here is to use nested ng-repeats:

<div ng-repeat="item in items">
    <div ng-repeat="subitem in item.subval">
        <div>{{subitem.attr1}}</div>
        <div>{{subitem.attr2}}</div>
    </div>
</div>

Example


If you don't like having that extra layer of divs, you can define this function in your controller to flatten the arrays:

$scope.allSubvals = function() {
    return [].concat.apply([], this.items.map(function (i) { return i.subval; }));
};

and then use it like this:

<div ng-repeat="item in allSubvals()">
    <div>{{item.attr1}}</div>
    <div>{{item.attr2}}</div>
</div>

Example

Upvotes: 3

Related Questions