2014-11-06 23 views
0

如何添加一個新的對象,可以從AngularJS的輸入表單中讀取?在AngularJS的JSON字典中添加對象

我的JSON:

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

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


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


我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 ={}; 
    }; 

    }] 
); 

我想有頁面,填寫所有輸入之後並提交按鈕ne w汽車將以JSON添加下一個ID。我應該添加什麼來實現這個目標?

回答

3

您的代碼是錯誤的。

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

工作小提琴:http://jsfiddle.net/wyorodt0/

+0

好的,但如何推新車成JSON文件? – 2014-11-06 13:12:32

+0

謝謝,這有助於很多! – 2014-11-06 13:37:23

+0

不客氣:) – 2014-11-06 13:39:12