AngularJS显示数组中的列表

时间:2014-11-10 22:05:20

标签: javascript arrays angularjs list angularjs-ng-repeat

我有一个返回数组的控制器,我试图将该数组的每个元素显示为列表。

我正在尝试做什么,这是行不通的:

<li ng-repeat="Name in names">
    <a ng-controller="PostsCtrl" href="#">{{response.text}}</a>
</li>

response.text 从控制器返回一个数组。

我也想知道,ng-repeat属性应该是什么值,任何唯一的字符串?

谢谢!

3 个答案:

答案 0 :(得分:13)

使用$ scope变量在控制器中定义数组:

app.controller('PostsCtrl', function($scope) {
    $scope.response = { text: ['hello', 'world'] };
}

然后在VARIABLE上使用ng-repeat,而不是控制器。

<div ng-controller="PostsCtrl">
    <ul>
        <li ng-repeat="name in response.text"><a href="#">{{name}}</a></li>
    </ul>
</div>

控制器仅用于定义您可以在该部分中使用的$ scope变量,并且不会将其用作变量本身。

答案 1 :(得分:2)

ngRepeat基本上就像一个for循环。没有默认值,您只需要为其提供您想要迭代的数据。因此,当您执行ng-repeat="name in names"时,它类似于在纯JavaScript中执行for(var name in names){}之类的操作。为了使其正常工作,您需要通过$scope将此数据传递到模板,如下所示:

&#13;
&#13;
var myApp = angular.module('myApp', []);

myApp.controller('PostsCtrl', ['$scope', function($scope){
    // Here the array would be your response.text:
    $scope.names = ['John', 'Jessie', 'Johanna', 'Joy', 'Mary', 'Peter', 'Sebastian', 'Erika', 'Patrick', 'Samantha'];

}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="PostsCtrl">
        I have {{names.length}} friends. They are:
        <ul>
          <li ng-repeat="name in names">
            [{{$index + 1}}] {{name}}.
          </li>
        </ul>
    </div>
</div>
&#13;
&#13;
&#13;

如需进一步阅读,请访问:https://docs.angularjs.org/api/ng/directive/ngRepeat

答案 2 :(得分:1)

除非您想为阵列中的每个项目使用新的控制器,否则您的控制器可能位于错误的属性上。

第二个问题,“response.text从控制器返回一个数组。”那么,这是你要重复的数组吗?

<div ng-controller="PostsCtrl">
  <li ng-repeat="item in response.text">
      <a href="#">{{item}}</a>
  </li>
</div>

然后是第三个问题,ng-repeat属性的值应该是什么:它应该是$scopeviewModel上任何有效数组的值。因此,response.text将是放在ng-repeat上的有效项,因为它是一个数组。如上所述,现在item中的每个项目都有reponse.text个对象。如果这是你想要的最远,你只需打印{{item}} - 如果item有属性,你可以做一些事情,例如,{{item.someProperty}}