角度双向绑定JSON?

时间:2016-04-07 11:02:58

标签: javascript angularjs json

实际上我在范围内有一个JSON。每当ng-model发生变化时,我都需要更改JSON值。在下面的示例JSON中,行集具有属性(CuId,Name,Quantity,Rate,Amount)。这些属性名称我必须绑定与控件(文本框),如ng-model = CuId。因此,每当相应的属性值发生变化时,JSON都需要更新。

请提供与此相关的任何示例或建议我如何实现此目标。

JSON:

 $scope.postJSON =   {
      "entityInfo": {
        "entity": "",
        "tenantId": "",
        "timeStamp": "2016-04-07T09:37:16.187Z"
      },
      "collections": {
        "Customer29Jan16": {
          "meta": {
            "parentreference": "***",
            "pkname": "***",
            "fkname": "***"
          },
          "rowset": [
            {
              "CuId": "test",
              "Name": "test",
              "Quantity": "test",
              "Rate": "test",
              "Amount": "test"
            }
          ],
          "rowfilter": []
        }
      }
    }

4 个答案:

答案 0 :(得分:4)

正如其他答案所提到的,您需要将整个树使用到要更改的属性。但是,他们没有提到由于rowset是一个数组,因此您还必须指定要访问的rowset元素。使用类似ng-model="postJSON.collections.Customer29Jan16.rowset[0].CuId"的内容。

答案 1 :(得分:2)

您必须将整个树放在ng模型中。像这样:

<input type="text" ng-model="postJSON.collections.Customer29Jan16.rowset.CuId" />

答案 2 :(得分:2)

<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].CuId" />

或者,为了使事情更紧凑,将行集放在范围内:

$scope.rowset = $scope.postJSON.collections.Customer29Jan16.rowset[0];

然后使用:

<input ng-model="rowset.CuId" />

答案 3 :(得分:1)

您已将postData添加到范围内,因此您可以绑定到各个属性。

<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].CuId" />
<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].Name" />
<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].Quantity" />
<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].Rate" />
<input ng-model="postJSON.collections.Customer29Jan16.rowset[0].Amount" />