ng-model不会更新已更改的表单内容

时间:2016-05-08 06:30:38

标签: angularjs angular-ngmodel angularjs-ng-model

我有一个包含删除条目按钮和添加条目按钮的表单。我想将更新后的表单字段数据输出到formData={},以便提交的数据是最新的。但是,删除字段集时,formData={}不会使用最新的数据条目信息进行更新,旧的表单数据仍然存在于formData={}中。 Here's the link for my code

1 个答案:

答案 0 :(得分:1)

尝试这样。

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

app.controller("MyCtrl" , function(){
  var formCtrl = this;
   formCtrl.forms ={
       formData:[{ name:""}]
   };
  
  formCtrl.addFields = function(){
    var name = {name:""};
     formCtrl.forms.formData.splice(formCtrl.forms.formData.length,0,name);
        
    };
  
  formCtrl.rmFields = function(form){
    var index  = formCtrl.forms.formData.indexOf(form);
       formCtrl.forms.formData.splice(index,1);
    }
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl as formCtrl">
   <table>
     <tr ng-repeat="form in formCtrl.forms.formData">
        <td> <input type="text" ng-model="form.name"></td>
        <td> <input type="button" ng-click="formCtrl.addFields()" value="Add" ng-show="$last"></td>
        <td> <input type="button" ng-click="formCtrl.rmFields(form)" value="Delete" ng-show="$index != 0"></td>
     </tr>
   </table> 
    <span>  <pre>{{formCtrl.forms | json }}</pre></span>
</div>