如何在 AngularJS 中停止提交表单

How to stop form submission in AngularJS

你可能会惊讶我为什么要这样做,但这是必须要做的。我无法解决,所以你能帮我吗..如果是,我们走吧!

I have a form, I want that if I click on submit, an action/event should be generated that stops the form submission, and tells me that your form is not submitted. That's it.

这是我的表格:

<div ng-app="myApp" ng-controller="myCtrl">

    <form>
        First Name: <input type="text" ng-model="firstName" required><br>
        Last Name: <input type="text" ng-model="lastName" required><br>

        <input type="submit" value="submit form"/>
    </form>

</div>

这是 AngularJS 控制器:

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {

        // Execute form submission
        // handle data and prevent redirect

    });
</script>

如果我问的是无关紧要的问题,我很抱歉,但我认为我现在无法做到这一点。

谢谢。

未经测试,您可以尝试换成

的提交按钮
<button ng-click="submit($event)">Submit form</button>

然后在你的控制器中:

$scope.submit = function($event) {
  $event.preventDefault();
}

通过不使用默认表单提交,您可以访问该事件并控制是否继续它。

AngularJs 公开了提交表单时应使用的 NgSubmit 指令

<form ng-submit="submit()">
    First Name: <input type="text" ng-model="firstName" required><br>
    Last Name: <input type="text" ng-model="lastName" required><br>

    <input type="submit" value="submit form"/>
</form>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {

        $scope.submit = function() {
            //do your thing
        };

    });
</script>

警告:不要结合使用 ng-click 和 ng-submit