如何使用角度JS来阻止表单提交进入按键?

jur*_*iks 1 javascript angularjs

HTML:

<button class="btn btn-primary btn-xs" ng-click="toggleForm()">Add translation</button>
<form class="block form-inline" id="translation_form" ng-show="form" ng-submit="addTranslation()">
    <h4>
        Enter a new translation for this text in {{language | uppercase}}:
        <button class="close" ng-click="toggleForm()" title="Close form">&times;</button>
    </h4>
    <hr />
    <div class="form-group">
        <input type="text" class="form-control" ng-model="formData.text" />
        <button type="submit" class="btn btn-primary btn-sm">Add</button>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

JS:

$scope.formData = {
    text: ''
};

$scope.toggleForm = function()
{
    if ($scope.form)
    {
        console.log('form closed', $scope.formData.text);
        $scope.form = false;
        $scope.formData.text = '';
    }
    else
    {
        $scope.form = true;

        if ($scope.history
            && ($scope.history.length > 0))
        {
            // set some default text
            $scope.formData.text = $scope.history[0].translation;
        }

        console.log('form opened', $scope.formData.text);
    }
};

$scope.addTranslation = function()
{
    console.log('adding translation', $scope.formData.text);
    // ajax call to post the text
    callback = function()
    {
        $scope.form = false;
        $scope.formData.text = '';
    }
};
Run Code Online (Sandbox Code Playgroud)

问题:当我打开表单时,键入一些文本并单击"添加"按钮,控制台中会记录以下文本:

form opened {some text here}
adding translation {some text here}
Run Code Online (Sandbox Code Playgroud)

但是,如果我打开表单并在聚焦于输入字段时点击Enter,则会记录以下内容:

form opened {some text here}
form closed {some text here}
adding translation {NO text here, because toggleForm empties the variable}
Run Code Online (Sandbox Code Playgroud)

显然,这是一个问题,因为我希望能够通过点击Enter来提交表单.问题是 - 为什么会发生这种情况以及如何预防?


编辑:通过将HTML结构更改为以下内容来避免此问题:

<div class="block" ng-show="form">
    <h4>
        Enter a new translation for this text in {{language | uppercase}}:
        <button class="close" ng-click="toggleForm()" title="Close form">&times;</button>
    </h4>
    <hr />
    <form class="form-inline" id="translation_form" ng-submit="addTranslation()">
        <div class="form-group">
            <input type="text" class="form-control" ng-model="formData.text" />
            <button type="submit" class="btn btn-primary btn-sm">Add</button>
        </div>
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

但是,我仍然没有回答为什么AngularJS甚至首先调用了关闭按钮的onclick事件......

小智 13

这个回应有点晚了,但是这个问题在今天下午让我的团队绊倒了 - 希望我们的经验会帮助别人.

仅仅type="button"为按钮对象添加属性就可以了 - 不需要任何其他更改.这实际上是一个很好的属性,可以添加到表单上任何不明确表单提交按钮的按钮.

<button class="close" type="button" ng-click="toggleForm()" title="Close form">&times;</button>
Run Code Online (Sandbox Code Playgroud)