2016-08-04 6 views
0

データが送信された後、配列に追加され、テーブルに表示されます。入力テキストフィールドに変更を加えると、それはテーブルに直接反映されます。この the input fields in here are directly changing the data value that has been added using the form, see the same values in last three rows入力フィールドはフォームからすでに送信されたデータの値を変更しますか?

HTML

<body ng-app="crud"> 
    <div ng-controller="ctrl"> 
    <form ng-submit="sub()"> 
     <label for="name">name</label> 
     <input type="text" name="name" ng-model="myForm.name" /> 
     <br><br> 
     <label for="contact">contact</label> 
     <input type="text" name="contact" ng-model="myForm.contact" /> 
     <input type="submit" value="sumit" ng-click="sub" /> 
    </form> 
    <div> 
     <table> 
     <tr ng-repeat="x in data track by $index"> 
      <td>{{x.name}}</td> 
      <td>{{x.contact}}</td> 
      <td> 
      <button type="button" ng-click="edit(x)">Edit!</button> 
      </td> 
     </tr> 
     </table> 
    </div> 
    </div> 
</body> 

JS

var app = angular.module("crud", []); 

app.controller("ctrl", ['$scope', function($scope) { 
    $scope.data = [{ 
    name: "ankur", 
    contact: 987898 
    }, { 
    name: "santosh", 
    contact: 987678 
    }, { 
    name: "tanvi", 
    contact: 98789877 
    }]; 
    $scope.count = 0; 
    $scope.myForm = {}; 
    $scope.myForm.contact = 0; 
    $scope.myForm.name = ""; 
    $scope.sub = function(myForm) { 
    $scope.data.push($scope.myForm); 
    }; 
}]); 

答えて

2

Angularjsよう

は、オブジェクト指向です。 同じオブジェクトを配列にプッシュするのではなく、コピーしてプッシュします。それはあなたのために賛成します。

$scope.sub = function(myForm) { 
    $scope.data.push(myForm); 
    }; 
+1

のJsで

$scope.data.push(angular.copy($scope.myForm)); 

別の方法

<form> <label for="name">name</label> <input type="text" name="name" ng-model="myForm.name" /> <br><br> <label for="contact">contact</label> <input type="text" name="contact" ng-model="myForm.contact" /> <input type="button" value="submit" ng-click="sub(myForm)" /> </form> 

私は、フォームの値を追加する必要があり、他の方法があります。それはちょうど最良の方法ではないように見えます:( –

+1

なぜこれが最善の方法ではないのか分かりませんが、配列内のアイテムをプッシュする別の方法は何でしょうか? –

+0

私は開発しようとしています –

関連する問題