简体   繁体   English

如何在Angular中使用ng-repeat迭代对象

[英]How can I iterate an object using ng-repeat in angular

I am facing problem in iterating an object,in which i have pushed the same property(value) from array of objects. 我在迭代对象时遇到问题,其中我从对象数组中推送了相同的property(value)。

    {
     id:1,
     id:2,
     id:3
    }

I want to display these id's in different rows of table like: 1 2 3 我想在表的不同行中显示这些ID,例如:1 2 3

Any help would be appreciated 任何帮助,将不胜感激

Try this: 尝试这个:

 angular.module('myapp', []) .controller("mycontroller", function($scope) { $scope.items = [ { "id": 1 } ,{ "id": 2 } ,{ "id": 3 } ]; }); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script> <div ng-app="myapp" ng-controller="mycontroller" class="container"> <h4>My items</h4> <ul class="list-group"> <li class="list-group-item" ng-repeat="item in items ">{{item.id}}</li> </ul> </div> 

Firstly, you can't have the same key repeated in an object. 首先,您不能在一个对象中重复相同的键。 Assuming you have an array of objects called 'idObjects': [{id: 1}, {id: 2}, {id: 3}], you can use ng-repeat on the tr element like this: 假设您有一个名为'idObjects'的对象数组:[{{id:1},{id:2},{id:3}],则可以在tr元素上使用ng-repeat,如下所示:

<table>
  <tr ng-repeat="idObj in idObjects">
    <td>{{ idObj.id }}</td>
  </tr>
</table>
var values = { id:1, id:2, id:3 };
var $scope.objToArr = [];
angular.forEach(values, function(value, key) {
  $scope.objToArr.push(value);
});

in your html 在你的HTML

<tr ng-repeat="idval in objToArr">
    <td>{{ idval}}</td>
  </tr>

it works even for different keys also. 它甚至适用于不同的键。

First convert the json object into an array and assign it to a $scope variable and then use ng-repeat to iterate over the array. 首先将json对象转换为数组,并将其分配给$scope变量,然后使用ng-repeat遍历数组。

Controller code: 控制器代码:

var jsonObj = { "id1":1, "id2": 2, "id3": 3 }; // your object

// constructing the array with your object;
$scope.idArray = Object.keys(jsonObj).map(function(k) { return jsonObj[k] });

HTML code: HTML代码:

<table>
    <tr ng-repeat="id in idArray track by $index">
        <td>{{ id }}</td>
    </tr>
</table>

Hope this solves the issue. 希望这能解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM