我正在使用angular生成多个元素的json数据。我正在输出
{"field":{"name":{"0":"a","1":"b"},"length":{"0":10,"1":20}}}
我希望jsondata变得复杂(以数组形式),例如:
{"field":[{"name":"a", "length":10},{"name":"b", "length":20}]}
我怎样才能做到这一点?
<!DOCTYPE html>
<html>
<head>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div ng-app="mainApp" ng-controller="JsonController as ctrl">
<div ng-repeat="a in [1,2] track by $index">
<input type="text" ng-model="task.field['name'][$index]">
<input type="number" ng-model="task.field['length'][$index]">
</div>
<pre>
{{task}}
</pre>
</div>
<script>
(function() {
angular.module("mainApp", []).controller("JsonController", function($scope) {
$scope.task = {};
});
}());
</script>
</body>
</html>
答案 0 :(得分:1)
<div ng-repeat="a in [1,2] track by $index">
<input type="text" ng-model="task.field[$index].name">
<input type="number" ng-model="task.field[$index].length">
</div>
$scope.task = {
field: []
};
虽然我根本不喜欢这种方法。为什么不在控制器中预先创建对象,只是迭代它们:
<div ng-repeat="t in task.field">
<input type="text" ng-model="t.name">
<input type="number" ng-model="t.length">
</div>
$scope.task = {
field: [{}, {}]
};