ngRepeat 迭代 angularjs 中的数组对象

ngRepeat iterate with array objects in angularjs

我正在尝试弄清楚如何使用 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 代码在这里

两件事,在 javascript 中

 $scope.peoples = response.data.People;

在 ng-repeat 中应该是

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

它是你 script.js 中的 peoples 而你在 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>

您需要修复 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>