我正在使用API,其中服务器期望带有动态密钥的json有效负载。 期待json:
[
{"hello" : "world"},
{"someuser" : "somepass"}
]
我在Angularjs中使用ng-model在UI上动态填充这些标头,并在用户点击提交后发送有效负载。
<li ng-repeat="header in headers track by $index">
<div ng-repeat="(key, value) in header">
<input type="text" placeholder="header key.." ng-model="key" />
<input type="text" placeholder="header value.." ng-model="value" />
<br/> key is {{key}} and value is {{value}}
</div>
</li>
修改了key
和value
的本地值,但看起来父对象不会被双向数据绑定修改。
我的后备代码使用固定密钥并在发送有效负载之前翻译结构,但我仍然想知道这是否可行。 翻译json:
[
{
"field": "someuser",
"value": "somepass"
},
...
]
HTML:
<li ng-repeat="header in headers track by $index">
<input type="text" placeholder="header key.." ng-model="header.field" />
<input type="text" placeholder="header value.." ng-model="header.value" />
</div>
</li>
编辑:修复了预期和翻译的json
答案 0 :(得分:0)
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<div ng-repeat="(key, value) in headers">
<input type="text" placeholder="header key.." ng-model="headers[$index]['key']" />
<input type="text" placeholder="header value.." ng-model="headers[$index]['value']" />
<br/>
key is {{key}} and value is {{value}}
</div>
<li>
<button ng-click="addHeader()">add header</button>
</li>
</ul>
{{headers | json}}
</body>
</html>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.headers = [];
$scope.addHeader = function() {
$scope.headers.push({key:"",value:""})
}
});