mateusz-c
mateusz-c

Reputation: 110

Adding Object in JSON dictionary in AngularJS

How can I add a new object which be read from input form in AngularJS ?

my JSON :

{
"1": {
    "name": "Audi",
    "year": "1993",

},
"2": {
    "name": "BMW",
    "year": "2012",
}
}


my Add.html:

<form name="addForm" ng-controller="AddCtrl" ng-submit="AddCtrl.newcar.(car)">
    <p>name: <input type="text" ng-model="AddCtrl.newcar.name"></p>
    <p>year: <input type="text" ng-model="AddCtrl.newcar.year"></p>
    <input type="submit" value="send" />
</form>


my AddCtrl :

angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
        $routeParams) {    
    $http.get('scripts/controllers/cars.json').success (function(data){

    });

    this.newcar = {};

    this.addCar = function(car) {
        car.name.push(this.name);
        this.newcar ={};
    };

  }]
);

I want to have page that after filling all inputs and cliking submit button new car will be added in JSON with next id. Where and what should I add to have achieve this ?

Upvotes: 0

Views: 3312

Answers (1)

Vinicius de Souza
Vinicius de Souza

Reputation: 156

Your code is wrong.

angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
        $routeParams) {    
    $scope.cars = [];
    $http.get('scripts/controllers/cars.json').success (function(data){
        $scope.cars = data;
    });

    $scope.addCar = function() {
      $scope.cars.push($scope.car.name);
    };

  }]
);

form

<form name="addForm" ng-controller="AddCtrl" ng-submit="addCar()">
    <p>name: <input type="text" ng-model="car.name"></p>
    <p>year: <input type="text" ng-model="car.year"></p>
    <input type="submit" value="send" />
</form>

Working fiddle:http://jsfiddle.net/wyorodt0/

Upvotes: 3

Related Questions