ngSubmit没有提交

时间:2014-09-25 09:48:09

标签: javascript angularjs html5 forms

我几乎是AngularJS的初学者,我正在尝试提交表单,如下所示:

<div ng-include="APP_URL + '/view/myResolver/searchForm.html'" ng-controller="MySearchFormController">   </div>

这是我的searchForm.html:

<div class="container">
<div class="row">
    <div class="col-md-14">
        <div class="well">
          <div class="col-md-9">
                <form ng-submit="submit()" class="form-horizontal clearfix" role="form" >
                        <div class="form-group">
                            <label for="teamName" class="col-md-3 control-label">Team name</label>
                            <div class="col-md-9">
                                <input type="text" ng-model="myName" id="myName" class="form-control">
                            </div>
                        </div>
           </div>
<div class="row">
                 <div class="col-md-0"></div>
                     <button ng-click="onFormReset()" class="btn btn-default">Reset</button>
                     <input type="submit" id="submit" class="btn btn-primary" value="Search"/>
</div>
                </form>

            {{teamName}}
      </div>
  </div>
</div>

更新

控制器:

angular.module('MyApp')
  .controller('MySearchFormController', ['$scope', function($scope){
    $scope.submit = function (){

      if ($scope.myName) {
        alert($scope.myName);
        $scope.teamName = this.teamName;
      }
    }
  }]);

目前正在发生的是文本自动显示在{{teamName}}字段中。 相反,我想让它只在onSubmit()上工作,即点击搜索按钮。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样:

function demo ($scope) {
  
  $scope.submit = function () {
    $scope.submitted = true;
  };
  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="demo">

  <form ng-submit="submit()">
    <input type="text" ng-model="teamName">
    <button>Submit</button>
  </form>
  
  <p ng-if="submitted">{{ teamName }}</p>
  
</div>

但是这不是最佳选择,因为一旦您提交了一次,$scope.submittedtrue,您将再次遇到同样的问题。

SO ,我建议您不要将{{ teamName }}绑定到与输入相同的引用:

function demo ($scope) {
  
  $scope.submit = function () {
    
    $scope.teamNameCopy = angular.copy($scope.teamName);
    
  };
  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="demo">
  
  <form ng-submit="submit()">
    <input type="text" ng-model="teamName">
    <button>Submit</button>
  </form>
  
  <p>{{ teamNameCopy }}</p>
  
</div>

答案 1 :(得分:0)

好的,问题已解决。

不幸的是,这是一个与错误关闭html标签有关的问题,而不是