子阵列上的ng-repeat不起作用?

时间:2014-12-09 15:48:25

标签: javascript json angularjs ng-repeat

我有这段代码:

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>

我一直试图弄清楚为什么ng-repeat不起作用但我无法解决它。我跟随CodeSchool上的AngularJS课程,并且还浏览了AngularJS教程,因为我在代码中找不到错误。我一直在这里寻找,也找不到解决方案。你们能指出我应该寻找什么,或者我有什么错误吗?

1 个答案:

答案 0 :(得分:3)

items没有名为subval的属性,因为items是一个数组。我认为这里要做的是使用嵌套的ng-repeat s:

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

Example

<小时/> 如果你不想拥有div的额外层,你可以在你的控制器中定义这个函数来展平数组:

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

然后像这样使用它:

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

Example