从同一个模型AngularJS添加多行

考虑到我有一个用户列表添加到我的系统,我不想一个接一个的过程。 然后我想看到一个用户表单(名称,电子邮件,密码字段),并在行的末尾我看到“添加另一行”button。

通过点击“添加另一行”button,另外一个用户表单会被添加到现有的表单之后。

我如何通过AngularJS中的一个POST请求发送多个用户?

您的控制器中应该有一组用户,每次按“添加另一个用户”时,都可以将新用户添加到arrays中。

控制器中的代码:

$scope.users = [{ name: "1" , email: "email1", password:"pas1" }, { name: "2" , email: "email2", password:"pas2"}];; $scope.addUser = function () { $scope.users.push({ name: "" , email: "", password:"" }); }; 

现在,在你的HTML将是一个列表与您的数组绑定的用户。 每次添加一个新用户,都会在html中添加一个新行,并在所添加的新用户的参数上绑定视图。

 <form ng-submit="submit()"> <div class="container"> <div class="col-md-5"> <li class="list-group-item col-xs-12" data-ng-repeat="user in users"> <input type="text" class="form-control" placeholder="Username" ng-model="user.name"> <input type="text" class="form-control" placeholder="Password" ng-model="user.name"> <input type="text" class="form-control" placeholder="Email" ng-model="user.name"> </li> <button class="col-xs-12" ng-click="addUser()">Add Another User</button> </div> 

添加一个函数也提交给你的控制器提交你想要的用户数组的方式。 希望它有帮助。

这是一些非常基本的Angular的东西。 这里是一个例子:

 <form name="usersForm" ng-submit="save()"> <div ng-repeat="user in users"> <label>Name:</label> <input type="text" ng-model="user.name" required /> <br/> <label>Email:</label> <input type="email" ng-model="user.email" required /> <hr/> </div> <button ng-click="newUser($event)">Add another one</button> <input type="submit" value="Save" ng-disabled="usersForm.$invalid || !users.length" /> </form> 

和一个控制器来处理数据:

 $scope.users = []; $scope.newUser = function($event){ // prevent submission $event.preventDefault(); $scope.users.push({}); } $scope.save = function(){ console.log($scope.users); // myService.saveUsers($scope.users); // $http.post("someUrlWhichHandlesListOfUsers", { users: $scope.users }); } 

的jsfiddle

你可以用$http.post()发布任何你想要的东西。 有什么不工作? 鉴于,你的用户存储在$ scope.users中,在你的“保存”方法,你可以写:

 $http.post('/someUrl', $scope.users). success(function(data, status, headers, config) { console.log('POSTed!'); }). error(function(data, status, headers, config) { console.log('Failed!'); }); 

而你的JSON对象将被发送到服务器。