输入字段是否更改了表单已提交的数据的值?

时间:2016-08-04 09:55:36

标签: javascript html angularjs

提交数据后,再添加到数组中,然后显示在表中。如果我在输入文本字段中进行更改,它将被直接反映到表中。

像这样 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);
   };
 }]);

1 个答案:

答案 0 :(得分:2)

Angularjs是面向对象的。 不要将同一个对象推入数组,而是复制并推送。那对你有利。

 $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>

在Js

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