克隆表格并克隆angularjs中相应形式的字段

时间:2017-06-29 11:55:50

标签: javascript angularjs

我有一个表单,其中包含一些字段和2个按钮,其中一个用于克隆整个表单,另一个用于仅克隆表单字段。我尝试使用ng-repeat,但是当我克隆表单然后尝试以原始形式克隆字段时,它也克隆了克隆形式的字段。如何限制重复形式的克隆。 这是我的HTML

    <!DOCTYPE html>
    <html>
      <head>
    <script data-require="angular.js@1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="MyController">
      <div ng-repeat="form in forms">
        <hr />
        <form name="myForm" ng-init="name = form.name">
          <br>

          <div ng-repeat="user in users">
          <input type="text" ng-model="user.name"/>
            <input type="text" ng-model="user.phone"/>
          </div><br>
          <button type="button" href="" ng-click="addUser()">Add user</button>
        </form>
      </div>
      <hr />
      <input type="button" value="Create form" ng-click="createForm()" />
    </div>
  </body>    
</html>

这是我的`script.js

    angular.module("myApp", []).controller('MyController',
    ['$scope', function($scope){
    $scope.forms = [{name: "form1"}];
    $scope.createForm = function(){
        $scope.forms.push({name: "form" + ($scope.forms.length + 1)});
    };
    $scope.saveForm = function(formScope){
        alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);            
    };
     $scope.users = [{name: 'John',phone: '098097770'},{name: 'Alice',phone: '765876598'}];
  $scope.addUser = function() {
    $scope.users.push({name: 'New user',phone: ''});
  };
  $scope.submit = function() {
    alert('Here are the users: ' + angular.toJson($scope.users));
  };
}]);

Plnkr Demo

1 个答案:

答案 0 :(得分:2)

这是工作的plnkr: plnkr

基本上,您需要将userform对象相关联,以使其对每个表单都是唯一的。

对于addUser,ng-repeat(嵌套的)和一个函数调用会有一些变化,你需要传递需要添加用户的表单的索引

$scope.forms = [
      {
        name: "form1",
        users: [
            {name: 'John',phone: '098097770'},
            {name: 'Alice',phone: '765876598'}
          ]
      }
    ];
    $scope.createForm = function(){
        $scope.forms.push({
          name: "form" + ($scope.forms.length + 1),
          users: [
            {name: 'John',phone: '098097770'},
            {name: 'Alice',phone: '765876598'}
          ]
        });
    };
    $scope.saveForm = function(formScope){
        alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);            
    };

  $scope.addUser = function(index) {
    $scope.forms[index].users.push({name: 'New user',phone: ''});
  };