使用ng-model修改(键,值)无法更新父对象

时间:2017-09-28 11:33:30

标签: angularjs angularjs-ng-repeat angularjs-ng-model

我正在使用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>

Plunker demo

修改了keyvalue的本地值,但看起来父对象不会被双向数据绑定修改。

现在解决方法

我的后备代码使用固定密钥并在发送有效负载之前翻译结构,但我仍然想知道这是否可行。 翻译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

1 个答案:

答案 0 :(得分:0)

HTML

<!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>

JS

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

app.controller('MainCtrl', function($scope) {
  $scope.headers = [];

  $scope.addHeader = function() {
    $scope.headers.push({key:"",value:""})
  }
});