2017-06-29 72 views
0

我有一個表單,其中有一些字段和2個按鈕,其中一個用於克隆完整表單,另一個用於僅克隆表單字段。我嘗試了ng-repeat,但是當我克隆表格然後嘗試克隆原始形式的字段時,它也克隆了克隆形式的字段。如何限制複製表單中的克隆。 這是我的HTML在angularjs中以相應形式克隆表單和克隆字段

<!DOCTYPE html> 
    <html> 
     <head> 
    <script data-require="[email protected]" 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

+0

你是什麼意思是隻克隆一個窗體vs克隆窗體域?沒有得到它 –

+0

@RahulArora請檢查plnkr演示。問題是在克隆表單後,我只想在各自的表單中添加用戶,而不是以兩種形式添加。 –

+0

請檢查我的答案,如果有幫助 –

回答

2

這裏是工作plnkr: plnkr

基本上,你需要鏈接userform對象,以便它對每個f唯一ORM。

會有一些變化NG-重複(嵌套一個)和一個函數調用ADDUSER,你需要通過針對用戶需要添加表格的指數

$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: ''}); 
    };