Matoy Matoy - 4 months ago 19
AngularJS Question

angular's ng-submit() directive does not submit while pressing enter on one of text fields

I've constructed a simple form using angular.
I want that once the user enter some value and then press enter - the ng-click function (in this case updateMsg({name: name,room: room})) will be run.

However, this code does not work like that.. the function run only after pressing the button (not like I want - enter keyboard value, then enter..)

Code is below...

help please?

Thanks

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

Answer

You should not use ng-click and ng-submit directives together. Add type="submit" to your button like this:

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

and keep only 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>

Also there is no point in doing ng-submit="updateMsg({name: name,room: room})" to pass your updated data like that. Since you are using ng-model you are ready to go. You can declare your scope vars initially in the controller and when the form gets submitted you can use them right away. Because of dual-binding your vars will be already updated:

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
    }
}]);

A small plunker to help you some more.