您好,我是 Angular 的新手,我有如下要求。
应用程序.js
$scope.fields = {
"fields": {
"LastName1": "ABC",
"FirstName1": "XYZ",
"LastName2": "123",
"FirstName2": "345",
"LastName3": "PQR",
"FirstName3": "ASD",
}
};
在我的 html 中,我需要遍历它并显示在
index.html
<tr ng-repeat="key in fields">
这似乎行不通。请帮忙。
我希望我的输出为
LastName1 ABC
FirstName1 XYZ
等等。
此外,如果用户对此进行了任何更改,我希望能够将更改推送回字段 Json。请帮忙。
最佳答案
您可以使用 (key, value) in object
语法。
你的情况:
<div ng-repeat="(key1, value1) in fields">
<li ng-repeat="(key2, value2) in value1">{{key2}} : {{value2}}</li>
</div>.
但是:
You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)
Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser when running for key in myObj. It seems that 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.
更多详情:https://docs.angularjs.org/api/ng/directive/ngRepeat
编辑:如果现在要更改对象怎么办?
你不能这样做:
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="value2" /><br />
{{key2}} : {{value2}}
</li>
</div>
为什么?因为 ng-model 将在当前范围内更改 value2
,而不是在您的对象 fields
中更改,因为您不使用点符号。
For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope.
更多详情:https://github.com/angular/angular.js/wiki/Understanding-Scopes
但是你可以:
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="fields[key1][key2]" /><br />
{{key2}} : {{value2}}
</li>
</div>
关于html - Angular Json 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155428/