gpt4 book ai didi

javascript - ng-model 命名问题,尝试构建一个数组,但得到了哈希值

转载 作者:行者123 更新时间:2023-12-02 15:58:53 25 4
gpt4 key购买 nike

我正在尝试使用 ng-model 构建一个数组,

<div ng-repeat="n in [1, 2, 3]">
<input type="text" class="form-control" ng-model="headers[$index].key">
<input type="text" class="form-control" ng-model="headers[$index].value">
</div>

当我执行angular.toJson ($scope.headers)时,我得到了:

{
"headers": {
"0": {
"key": "xxx",
"value": "yyy"
}
}
}

但我想要这个,

{
"headers": [
{
"key": "xxx",
"value": "yyy"
}
]
}

这不可能吗?

最佳答案

你是这个意思吗?

DEMO

index.js

<!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.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
<div ng-repeat="object in transformedData">
<input type="text" class="form-control" ng-model="object.key">
<input type="text" class="form-control" ng-model="object.value">
</div>

<pre>{{transformedData}}</pre>
</body>

</html>

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

var data = {
"headers": {
"0": {
"key": "xxx",
"value": "yyy"
}
}
};

$scope.transformedData = transformData(data.headers)

function transformData(data){
var arr = [];
for(var key in data){
arr.push(data[key])
}
return arr;
}

});

关于javascript - ng-model 命名问题,尝试构建一个数组,但得到了哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31375563/

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