javascript - 输入字段更改表单已提交的数据的值?

标签 javascript html angularjs

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

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

最佳答案

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);
   };

关于javascript - 输入字段更改表单已提交的数据的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38764126/

相关文章:

angularjs - AngularJS 中的 "Computed Properties"

javascript - 转义 jQuery 选择器

css - <div style ="height:100%"> 由于上层菜单的高度大于页面。如何解决这个问题?

javascript - 错误 : <Route> elements are for router configuration only and should not be rendered in react-router v4

javascript - 如何在angular js和html5中显示来自javascript对象的特定代码的名称

javascript - 以内圆和外圆为界的三 Angular 形

javascript - 重置作为参数传递的 select 的值

javascript - AngularJS:向 ng-repeat 内的图像添加切换功能

javascript - 单击按钮时 JQuery OnClick 不起作用

javascript - 在 foreach 循环之后初始化插件