我正在尝试用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="[email protected]" 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/

10-16 19:52