【问题标题】:AngularJS ng-submit event handler gets called even when not submitting即使未提交,AngularJS ng-submit 事件处理程序也会被调用
【发布时间】:2014-02-18 19:45:04
【问题描述】:

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

但在实现任何验证之前,我注意到即使没有提交表单,事件处理程序也会被调用。在下面的示例中,当我单击“添加项目”按钮时会调用它:

<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>  

还有 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?");
     };
  }]);

在这里看我的小提琴:

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

这应该发生吗?在我看来,ng-submit 不只是在表单提交时触发......我做错了什么吗?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    相信您需要添加type="button" 以避免意外调用提交。更新了小提琴并似乎修复了它:

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

    <button type="button" ng-click="doSomething()">Test</button>
    

    【讨论】:

    • 这是正确的。 "A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit""
    • 天哪,好尴尬!我盲目地假设问题出在 Angular 上。感谢您指出这一点!
    • 链接到@Tom对html规范w3.org/TR/html-markup/button.html的引用。
    猜你喜欢
    • 2014-11-22
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多