gpt4 book ai didi

javascript - AngularJS 中的动态 ng-repeat

转载 作者:行者123 更新时间:2023-11-29 19:08:44 24 4
gpt4 key购买 nike

我的 Angular Controller 是

$scope.dyna = [
{ "name": "parshuram", "age": 24 },
{ "name": "Tejash", "age": 26 },
{ "name": "Vinayak", "age": 25 }
];

我的html
<table>
<tbody>
<tr ng-repeat="test in dyna">
<td>{{test.name}}</td>
<td>{{test.age}}</td>
</tr>
</tboody>
</table>

这工作正常,并输出
Parshuram 24
Tejash 26

但是,如果将另一个变量添加到我的范围变量中,我需要在我的 html 表中进行更改:
  $scope.dyna = [
{ "name": "parshuram", "age": 24 ,"void": true},
{ "name": "Tejash", "age": 26,"void" : false }
];

<table>
<tbody>
<tr ng-repeat= "test in dyna">
<td>{{test.name}}</td>
<td>{{test.age}}</td>

<!-- I don't want to have to add this, the columns should be added dynamically -->
<td>{{test.void}}</td>
</tr>
</tboody>
</table>

在这种情况下,是否可以动态生成列,例如通过从范围中获取我的所有对象变量?

最佳答案

ng-repeat可以循环对象 key/values as well :

<table>
<tbody>
<tr ng-repeat= "test in dyna">
<td ng-repeat="(key, value) in test">
{{value}}
</td>
</tr>
</tbody>
</table>

但是,如上面链接的文档中所述,与 ng-repeat 相比,存在一些限制。适用于数组:

  • The JavaScript specification does not define the order of keys returned for an object, so Angular relies on the order returned by the browser when running for key in myObj. Browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated. See the MDN page on delete for more info.

  • ngRepeat will silently ignore object keys starting with $, because it's a prefix used by Angular for public ($) and private ($$) properties.

  • The built-in filters orderBy and filter do not work with objects, and will throw an error if used with one.

关于javascript - AngularJS 中的动态 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40800130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com