清除angularJs形式

时间:2016-02-18 10:04:03

标签: angularjs angularjs-forms

我正在使用AngularJs 1.4并有一个输入表单。我在表单末尾有一个重置,取消和提交按钮。单击时,所有表单元素必须设置为默认值。但是,当我单击submitForm按钮时,resetForm函数也会随reset函数一起被调用。请让我知道我哪里出错了。表单字段也没有重置。

<form class="form-horizontal" name="myForm" ng-submit="submitForm(myForm.$valid)" novalidate><!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<div class="form-group" ng-class="{ 'has-error' : myForm.ipaddresses.$invalid && !myForm.ipaddresses.$pristine }">
  <label class="col-sm-3 control-label">IP</label>
  <div class="col-md-6"><textarea name="ipaddresses" class="form-control" ng-model="ipaddresses" ng-minlength="8" ng-requied="!myForm.myFile"></textarea></div>
    <p ng-show="myForm.ipaddresses.$invalid && !myForm.ipaddresses.$pristine" class="help-block">Hostname or IP Addresses are mandatory</p>
  </div>
  <div class="hr-line-dashed"></div>
  <div class="form-group">
    <label class="col-sm-3 control-label">File Upload</label>
    <div class="col-lg-6">
      <div class="upload-file">
        <input type="file" file-model="myFile" class="upload-demo" id="upload-demo" ng-requied="!myForm.ipaddresses">
        <label for="upload-demo" data-title="Select file">
          <span class="ng-binding">Comma separated CSV file...</span>
        </label>
      </div>
    </div>
  </div>
  <div class="hr-line-dashed"></div>
  <div class="form-group"><label class="col-sm-3 control-label">Mode</label>
    <div class="col-md-3">
      <select name="mode" class="form-control m-b" ng-required="true">
        <option>Enable</option>
        <option>Disable</option>
      </select>
    </div>
  </div>
  <div class="hr-line-dashed"></div>
   <div class="form-group" style="margin-top: 8%;">
    <div class="col-sm-4 col-sm-offset-4">
      <button class="btn btn-info">Cancel</button>
      <button class="btn btn-warning" ng-click="resetForm(myForm)">Reset</button>
      <button class="btn btn-primary" type="submit" ng-disabled="myForm.$invalid">Next >></button>
    </div>
  </div>
</form>

在我的控制器中,我有以下代码:

 $scope.submitForm = function(isValid) {
    // check to make sure the form is completely valid
    if (isValid) {
      alert('our form is amazing');
    }
};

 $scope.resetForm=function(myForm){
        console.log('came here....')
        myForm.ipaddresses=null;
    }

2 个答案:

答案 0 :(得分:1)

只需将myForm.ipaddresses=null;更改为$scope.ipaddresses='';

它应如下所示:

$scope.resetForm=function(myForm){
    console.log('came here....');
    $scope.ipaddresses='';
}

答案 1 :(得分:0)

你可以使用$ setPristine();到形式,作为角度的文件 https://docs.angularjs.org/api/ng/type/form.FormController

  

&#34;当我们想要时,将表格设置回原始状态通常很有用   重用&#39;保存或重置后的表单。&#34;

期待帮助