【问题标题】:ng-repeat for object (hash) in AngularJS [duplicate]AngularJS中对象(哈希)的ng-repeat [重复]
【发布时间】:2014-07-05 07:04:49
【问题描述】:

学习ng-repeat的正常方式如下

<li ng-repeat="item in items">{{item.attribute}}</li>

你会有一个控制器,比如

app.controller('myCtrl', function($scope) {
     $scope.items = [
          { name : kitten, attribute : value },
          { name : puppy, attribute : value }
     ];
});

这很好,但是当我深入了解我的应用程序并且必须通过数组索引引用项目时,它会变得很笨拙。修改小猫属性的函数会去:

$scope.items[0].attribute = value;

我更愿意:

app.controller('myCtrl', function($scope) {
     $scope.items = {
          'kitten' : {attribute : value },
          'puppy' : { attribute : value }
     };
});

这样我可以

$scope.items.kitten.attribute = NEW
-or-
$scope.items["kitten"].attribute = NEW
(are these equivalent??  I think so)

但是我将如何遍历它们呢?

<li ng-repeat="item in items">{{item.attribute}}</li>

不工作。

【问题讨论】:

  • 除了tymeJV的回答,请养成经常查看the documentation的习惯。所有的答案都在那里。
  • 文档很神秘。这里的答案总是有帮助的。我是 Angular 的新手。请收回你的DV。

标签: javascript angularjs model-view-controller


【解决方案1】:

您可以使用以下语法:

ng-repeat="(k, v) in o"

k是被迭代的属性的键,v是值,o是被迭代的对象。

【讨论】:

  • 我就知道你会回答这个问题。
  • @dckuehn - 刚吃完午饭回来:D
  • 那么它会是 o 中的(名称,属性)吗?如果我有不同的属性,并且不想在 o 中专门指定每个属性(名称、attr1、attr2、...)怎么办
  • 如果你想要猫的名字,那么它将是
  • {{key}}
  • 如果你想要那些其他属性值它只是简单的
  • {{values.attribute}}
  • 如果你有嵌套的属性你会得到 values.attribute.xxx.yyy
猜你喜欢
相关资源
最近更新 更多
热门标签