问题
I have a form which has a delete entry button and an add entry button. I want to output the updated form field data to formData={}
, so that the submitted data will be up-to-date. However, when a fieldset is deleted, formData={}
is not updated with the newest data entry information and the old form data still exist in formData={}
. Here's the link for my code
回答1:
try like this.
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>
来源:https://stackoverflow.com/questions/37096954/ng-model-wont-update-the-changed-form-content