【问题标题】:AngularJS display list from an arrayAngularJS 显示数组中的列表
【发布时间】:2023-03-10 18:05:01
【问题描述】:

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

我正在尝试做的事情,但不起作用:

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

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

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

谢谢!

【问题讨论】:

  • namesresponse 看起来像什么?我知道你提到了一个数组,但它们都是数组吗?
  • {{ JSON.stringify(response.text) }} 怎么样?

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


【解决方案1】:

使用 $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变量,本身并不用作变量。

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

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

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'];

}]);
<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>

更多阅读请访问:https://docs.angularjs.org/api/ng/directive/ngRepeat

【讨论】:

  • 非常感谢,抱歉我不能选择多个正确答案。
【解决方案3】:

你的控制器可能在那里设置了错误的属性,除非你想为数组中的每个项目一个新的控制器。

第二个问题,“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 上的有效项目,因为它是一个数组。正如我在上面所说的,现在reponse.text 中的每个项目都有一个item 对象。如果这是你想要的,你可以简单地打印{{item}}——如果item有属性,你可以做一些类似的事情,例如,{{item.someProperty}}

【讨论】:

  • 谢谢,可惜我不能选择多个正确答案!
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
相关资源
最近更新 更多