我的 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/