即使不提交,也会调用AngularJS ng-submit事件处理程序

Sim*_*een 10 angularjs

我正在尝试使用angular-ui设置表单验证.我想在提交之前检查表单是否有效,所以我已经设置了一个ng-submit事件处理程序.

但在实现任何验证之前,我注意到即使不提交表单也会调用事件处理程序.在下面的示例中,单击Add Item按钮时会调用它:

<div ng-app="app">
    <div ng-controller="ctrl">
        <form name="myForm" ng-submit="sub()" novalidate>                    
            <div ng-repeat="item in items">
                <ng-form name="row">
                    <input type="text" name="value" ng-model="item.value" required />                    
                </ng-form>
            </div>         
            <button ng-click="addItem()">Add Item</button>        
            <input type="submit" value="Submit"/>
        </form>
    </div>
</div>  
Run Code Online (Sandbox Code Playgroud)

和JS:

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

 app.controller('ctrl', ['$scope', function($scope) {
     $scope.items = [];
     $scope.addItem = function() {
         $scope.items.push({ value: $scope.items.length });
     };

     $scope.sub = function() {
         alert("submitted?");
     };
  }]);
Run Code Online (Sandbox Code Playgroud)

看到我的小提琴:

http://jsfiddle.net/UvLBj/2/

这应该发生吗?我觉得ng-submit不仅仅是在表单提交上被解雇了......我做错了吗?

sha*_*ain 24

相信你需要添加type ="button"以避免意外调用提交.更新了小提琴并似乎解决了它:

http://jsfiddle.net/UvLBj/3/

<button type="button" ng-click="doSomething()">Test</button>
Run Code Online (Sandbox Code Playgroud)

  • 这是对的."`没有指定type属性的按钮元素表示与按钮元素相同的东西,其type属性设置为"submit"`" (6认同)