angularjs - ng-repeat:从 JSON 数组对象访问键和值 [英] angularjs - ng-repeat: access key and value from JSON array object

查看:23
本文介绍了angularjs - ng-repeat:从 JSON 数组对象访问键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的 JSON 数组对象.

I have JSON Array object as shown below.

$scope.items = 
    [
    {Name: "Soap",  Price: "25",  Quantity: "10"},
    {Name: "Bag",   Price: "100", Quantity: "15"},
    {Name: "Pen",   Price: "15",  Quantity: "13"}
];

我想在 angular.js 中使用 ng-repeat 分别获取键和值.我已经尝试了以下代码,但它不起作用.

I want to get the keys and values separately using ng-repeat in angular.js. I have tried the following code but its not working.

<tr ng-repeat="(key, val) in items">
  <td>{{key}}</td> 
  <td>{{val}}</td>
 </tr> 

我相信问题出在大括号["和]"上.谁能建议我如何解决这个问题?

I believe the problem is with the braces '[' and ']'. Can anyone please suggest me how the issue can be resolved ?

非常感谢您的回复.我已经试过你的代码和它的工作.但我真正的要求是显示如下所示的项目.

Thank you so much for the reply. I have tried your code and its working. But my real requirement is display the items as shown below.

Name     Price  Quantity
Soap        25  10
Bag        100  15
Pen         15  13

我在 html 中使用了一些 .但屏幕上没有显示任何内容.代码如下所示.

I am using some <tr> and <td> in html. But nothing getting displayd in screen. The codes are shown below.

<table>  
 <tr ng-repeat="item in items">
  <tr ng-repeat="(key, val) in item">
      <td>{{key}}</td>
      <td>{{val}}</td>
  </tr>
</tr> 
</table>

我知道在另一个 中的 是 html 不允许的.我尽力了.但没有运气.如果你能在这方面帮助我,那就太好了.提前致谢.

I know that <tr> inside of another <tr> is not permitted by html. I tried by best.But no luck. It will be great if you could help me in this. Thanks in advance.

推荐答案

你有一个对象数组,所以你需要使用 ng-repeat 两次,比如:

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

示例:http://jsfiddle.net/Vwsej/

请注意,不能保证对象中的属性顺序.

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

示例:http://jsfiddle.net/Vwsej/2/

这篇关于angularjs - ng-repeat:从 JSON 数组对象访问键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆