ng单击后调用的ng提交操作

ng-submit action called after ng-click

本文关键字:ng 提交 操作 调用 单击      更新时间:2023-09-26

我是AngularJS的新手。我正在尝试奥在AngularJS书中提到的一个演示。我知道,当表单中有一个输入字段时,在该输入中点击回车键,会触发ng-clickng-submit操作。然而,在我的情况下,我只有一个输入字段,即使我没有在输入字段内按enter键,每次单击重置按钮时,我的ng提交操作都会被调用。这是代码。

<!DOCTYPE html>
<html ng-app="">
<head lang="en">
    <meta charset="UTF-8">
    <title>Form Submit Action</title>
</head>
<body>
    <form ng-submit="requestFunding()"
          ng-controller="FormController">
        Estimate :
        <input ng-model="estimate"/>
        <br/>
        Recommended :
        {{recommended}}
        <br/>
        <Button>Fund My Start Up</Button>
        <Button ng-click="reset()">Reset</Button>
    </form>
    <script src="Scripts/angular.js"></script>
    <script>
        function FormController($scope)
        {
            $scope.estimate = 0;
            computeNeeded = function(){
                $scope.recommended = $scope.estimate * 10;
            };
            $scope.$watch('estimate', computeNeeded);
            $scope.requestFunding = function()
            {
                window.alert("Add More Customers First");
            };
            $scope.reset = function()
            {
                $scope.estimate = 0;
            };
        }
    </script>
</body>
</html>

是否存在逻辑或概念上的错误?当我使用AngularJS时,请告诉我提交和重置表单的正确方式。

在stard.html中,您需要设置type="reset"以指示这是一个重置按钮:

 <button type="reset" ng-click="reset()">Reset</button>

但你会从角度上看到这种方法的问题,正如这个演示所示。单击Reset时,输入设置为空,而不是您在代码中指定的0

$scope.reset = function() {
    $scope.estimate = 0;
};

出现此问题的原因是$scope.reset首先运行,并且被浏览器的重置按钮的默认操作覆盖(清除表单输入)。

在angular中,您需要做不同的操作,您需要preventDefault并使用form.$setPristine()来重置表单输入状态:

<form name="form" ng-submit="requestFunding()" ng-controller="FormController"> //give the form a name
    Estimate :
    <input ng-model="estimate" />
    <br/>Recommended : {{recommended}}
    <br/>
    <button>Fund My Start Up</button>
    <button ng-click="$event.preventDefault(); reset(); form.$setPristine();">Reset</button>
  </form>

演示

从文档中引用$setPristine:

将窗体设置为其原始状态。

可以调用此方法来删除"ng dirty"类,并设置形成其原始状态(ng原始类)。此方法还将传播到此表单中包含的所有控件。

当我们需要时,将表单设置回原始状态通常很有用保存或重置表单后"重新使用"表单。

不用ng提交,用ng点击调用requestFunding(),它将解决您的问题。

如果您的按钮正在提交表单,请为其提供适当的类型以进行控制-例如:

<button type="reset" value="Reset">
<button type="submit" value="Submit">