javascript - 在文本字段之一上按 Enter 键时, Angular ngsubmit() 指令不会提交

标签 javascript angularjs

我使用 Angular 构建了一个简单的表单。 我希望一旦用户输入一些值然后按 Enter 键 - ng-click 函数(在本例中 updateMsg({name: name,room: room}))就会运行。

但是,这段代码不是这样工作的..该函数仅在按下按钮后运行(不像我想要的 - 输入键盘值,然后输入..)

代码如下...

请帮忙?

谢谢

<body>
    <div class="Member">
        <h1>Sign In</h1>
        <form name="myForm" ng-submit="updateMsg({name: name,room: room})">
            Please enter your details:
            <br>
            Name: <input name="name" ng-model="name" autocomplete="off">
            <br>
            Room: <input name="room" ng-model="room" autocomplete="off">
            <br>
            <button type="button" ng-click="updateMsg({name: name,room: room})">

            Enter
            </button>
        </form>
    </div>
</body>

最佳答案

您不应同时使用 ng-clickng-submit 指令。将 type="submit" 添加到您的按钮,如下所示:

<button type="submit">Enter</button>

并仅保留ng-submit:

    <form name="myForm" ng-submit="updateMsg({name: name,room: room})">
        Please enter your details:
        <br> Name:
        <input name="name" ng-model="name" autocomplete="off">
        <br> Room:
        <input name="room" ng-model="room" autocomplete="off">
        <br>
        <button type="submit">Enter</button>
    </form>

此外,执行 ng-submit="updateMsg({name: name,room: room})" 来传递更新的数据是没有意义的。由于您正在使用 ng-model,您就可以开始了。您可以最初在 Controller 中声明范围变量,提交表单后您可以立即使用它们。由于双重绑定(bind),您的变量将已经更新:

angular
.module('myApp', [])
.controller('MemberController', ['$scope', function($scope) {
    $scope.name = '';
    $scope.room = '';
    $scope.updateMsg = function() {
        // use updated $scope.name in here
        // use updated $scope.room too
    }
}]);

plunker为您提供更多帮助。

关于javascript - 在文本字段之一上按 Enter 键时, Angular ngsubmit() 指令不会提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38440775/

相关文章:

PHP 表单 ActionScript 不工作

javascript - Angular Meteor 应用程序在本地主机中运行,但在部署到服务器时失败

javascript - 在 AngularJS 中将 JSON 对象绑定(bind)为 radio 数据

javascript - 检测Vue.js中跨域iframe内的内容变化?

javascript - 来自 CosmosDB JavaScript 的 Azure 函数更改源

javascript - 我想在 JavaScript 代码中保存用户首选项

javascript - AngularJS 中的 GetElementById

javascript - Angular js : can't recognize ngTable in Controller

angularjs $modal 关闭模态

javascript - 带分页的 Angular 搜索