ngRepeat使用angularjs中的数组对象进行迭代

时间:2018-07-10 15:04:02

标签: javascript arrays angularjs angular1.6

我正在尝试弄清楚如何使用ngrepeat迭代数组

如果我有如下数据数组

{
  "People": [{
      "name": "Andrew Amernante",
      "rating": 3,
    },
    {
      "name": "Frank Wang",
      "rating": 5,
    },
    {
      "name": "Chang Wang",
      "rating": 5,
    }
  ]
}

在Controller中,我有这些代码段。

app.controller('mainController', function($scope, $http) {
  $http.get('people.json').
  then(function onSuccess(response) {
    console.log(response);
    $scope.peoples = response.data;

  }).
  catch(function onError(response) {
    console.log(response);
  });
});

而且,我想遍历数组并在列表中显示三个名称。

<ul class="nav">
  <li ng-repeat="obj.peoples track by $index">
    <a href="#/">{{obj.name}}</a>
  </li>
</ul>

但是,我无法获得名称,对此有任何想法吗?

仅供参考-我在这里使用Angular 1.6.5版本。

Plunkr这里的代码

3 个答案:

答案 0 :(得分:4)

您需要修复HTML代码。

应该改为ng-repeat="obj.peoples track by $index"而不是ng-repeat="obj in peoples.People track by $index"

请参见下面的演示。

angular.module('app', [])
  .controller('mainController', function($scope, $http) {
    // mocked, equivalente to `$scope.peoples = response.data`
    $scope.peoples = {
      "People": [{
          "name": "Andrew Amernante",
          "rating": 3,
        },
        {
          "name": "Frank Wang",
          "rating": 5,
        },
        {
          "name": "Chang Wang",
          "rating": 5,
        }
      ]
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='mainController'>
  <ul class="nav">
    <li ng-repeat="obj in peoples.People track by $index">
      <a href="#/">{{obj.name}}</a>
    </li>
  </ul>

</div>

答案 1 :(得分:1)

这是您script.js中的人物,并且您在html中使用obj

$http.get('people.json').
        then(function onSuccess(response) {
            console.log(response);
            $scope.peoples = response.data;

        }).

将您的html更改为以下代码,

<li class="active" ng-repeat="item in peoples.People">
       <a href="#/">{{item.name}}<span class="glyphicon glyphicon-play"></span></a>
 </li>

答案 2 :(得分:-1)

两件事,在javscript中

 $scope.peoples = response.data.People;

并且在ng-repeat中应该是

ng-repeat="people in peoples track by $index"