使用angularjs将表单中的输入值添加到json对象

时间:2016-05-26 20:10:37

标签: angularjs

我正在尝试使用angularjs将输入字段的值添加到json对象我写了一些代码,但它不起作用,请我需要帮助

脚本部分

 <script>
var app = angular.module("exampleApp", []);
            app.controller("defaultCtrl", function ($scope, $http) {
                $scope.loadData = function () {
                    $http.get("productData.json").then(function (response) {
                        console.log("Status: " + response.status);
                        console.log("Type: " + response.headers("content-type"));
                        console.log("Length: " + response.headers("content-length"));
                        $scope.products = response.data;
                    });

                    $scope.products = {name:'',age:'',isDead:''};
                    $scope.resurrect = function(item){
                        item.isDead = false;
                    };

                   $scope.addnew = function(){
                        $scope.products.mname = $scope.products.name;
                        $scope.products.mage = $scope.products.age;
                        $scope.products.misDead = $scope.products.isDead;
                   };
                }

            });
</script>

productData.json

[
   { "name": "Tommen Baratheon", "age": "23", "isDead": true },
   { "name": "Roose Bolton", "age": "32", "isDead": false },
   { "name": "Theon Greyjoy", "age": "27", "isDead": true},
   { "name": "Cersei Lannister", "age": "31", "isDead": false}
]

表单部分

<form>
<input type="text" placeholder="Enter Charater name" class="form-     control" ng-model="products.mname">
<input type="number" placeholder="Enter Charater age" class="form-control" ng-model="products.mage">
<input type="text" placeholder="Enter True or false" class="form-control" ng-model="products.misDead">
<input type="submit" value="andNew" ng-submit="addnew()"></form>

1 个答案:

答案 0 :(得分:0)

所以第一个问题是$scope.products是一个数组。您的标记被绑定,就好像它只是一个对象一样。

<form>
    <div ng-repeat="p in products">
        <input type="text" placeholder="Enter Charater name" class="form-control" ng-model="p.name">
        <input type="number" placeholder="Enter Charater age" class="form-control" ng-model="p.age">
        <input type="text" placeholder="Enter True or false" class="form-control" ng-model="p.isDead">
        <input type="submit" value="andNew" ng-submit="addnew()">
    </div>
</form>

另一个问题是你有像products.mname这样的绑定,但该字段实际上是name。您遇到的下一个问题是,当您真正将其初始化为空数组时,您正在将products初始化为object

$scope.products = [];

您将遇到的下一个问题是addnew。它只需要将一个新对象推送到数组:

$scope.addnew = function() {
  $scope.products.push({});
};

这将导致在div内呈现新的form