简体   繁体   中英

post json object in Angularjs

i ask this question ago but don't get answer. i have a form that by filling it create json object and post to server.this form repeat in several time. The data entry forms can be repeated several times.

<div ng-repeat="office in offices">
   <input type="text" ng-model="officeName">
   <input type="text" ng-model="office.employee">
   <input type="text" ng-model="office.employee">
   <button ng-click="addOffice()">Add New Office</button>
</div>

suppose my objects are

public class FormData{
   private List<Data> all;
}
public class Data{
  private String officeName;
  private List<Employee> list;
}
public class Employee{
  private String name;
}

how create json objects and bind data that get from form bind to this objects? And how create form entry data?(how set ng-model)

You can do something like this:

 var app = angular.module('app', ['ngMockE2E']); app.controller('myController', function($scope, $http) { $scope.offices = []; $scope.addOffice = function() { $scope.offices.push({ employees: [] }); }; $scope.addEmployee = function(office) { office.employees.push({}); }; $scope.submitOffices = function() { $http.post('/offices', $scope.offices) .success(function() { // Handle success. }).error(function() { // Handle error. }); }; }); 
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-mocks.js"></script> <div ng-app='app' ng-controller='myController'> <button ng-click="addOffice()">Add New Office</button> <div ng-repeat="office in offices" ng-if="offices"> <form name="officesForm" novalidate ng-submit="submitOffices()"> Company Name: <input type="text" ng-model="office.name"> <div> Employees: <ng-form name="employeForm{{$index}}" ng-repeat="employee in office.employees"> <div> <input type="text" ng-model="employee.name"> </div> </ng-form> <button type="button" ng-click="addEmployee(office)">Add Employee</button> </div> <button type="submit">submit</button> </form> </div> <pre>{{ offices | json }}</pre> </div> 

The sandboxed iframe prevents it from posting so here it is on plunker.

http://plnkr.co/edit/2eGVa3tg3TtIhFXNpUGI?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM