简体   繁体   中英

What is the default behavior of ng-submit?

I have new to AngularJS and am now learning this todo-mvc example . One thing confusing to me is the behavior of the ng-submit in the following code from the index.html:

<form id="todo-form" ng-submit="addTodo()">
    <input id="new-todo" placeholder="What needs to be done?" ng-model="newTodo" autofocus>
</form> 

Here is the code for the addToDo() function:

$scope.addTodo = function () {
    var newTodo = $scope.newTodo.trim();
    if (!newTodo.length) {
        return;
    }

    todos.push({
        title: newTodo,
        completed: false
    });

    $scope.newTodo = '';
};

As you can see, there is nowhere that shows what event ng-submit is supposed to correspond to. I am guessing that ng-submit is meant to handle the enter event of the input field. However, I can't find relevant information in the official document . So, what is the default behavior of ng-submit ? Namely, I would like to know what events correspond to "submit" in various situations. In this particular example, is it true that "submit" means enter of the input field?

Thank you very much.

This is written at the top of the documentation you put as link:

Enables binding angular expressions to onsubmit events.

-----------UPDATE-------------

In your comment below, you held:

onsubmit event occurs when you click a submit button

That's not exact.

First, let's be sure about the event thrown by ngSubmit directive.
In the angular-scenario.js , there is this code:

var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
  element.bind('submit', function() {
    scope.$apply(attrs.ngSubmit);
  });
});

Moreover, if you refers to the HTML 2.0 spec, about the Form Submission , (thus submit event):

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

Also, from Angular's code, line 15527 (depending on current version):

* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
 * or {@link ng.directive:ngClick ngClick} directives.
 * This is because of the following form submission rules in the HTML specification:
 *
 * - If a form has only one input field then hitting enter in this field triggers form submit
 * (`ngSubmit`)
 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
 * doesn't trigger submit
 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM