user141464 user141464 - 6 months ago 29
AngularJS Question

adding input values from form to json object using angularjs

am trying to add the value of input field to json object using angularjs i wrote some codes but it doesn't work, please i need help

script section

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

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

Answer

So the first problem is that $scope.products is an array. Your markup is bound as if it's a single object though.

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

The other problem was that you had bindings like products.mname, but the field is actually name. The next problem you have is you're initializing products as an object when you really should just initialize it as an empty array:

$scope.products = [];

The next problem you'll have is addnew. It needs to just push a new object on to the array:

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

That will cause a new div to be rendered inside the form.

Comments