2014-03-02 122 views
1

我有AngularJS的新手,现在正在学习this todo-mvc example。有一点困惑,我是ng-submit的在index.html下面的代码的行为:ng-submit的默认行为是什么?

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

这里是为addToDo()函数的代码:

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

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

    $scope.newTodo = ''; 
}; 

正如你所看到的,无处显示ng-submit应该对应的事件。我猜ng-submit是为了处理input字段的enter事件。但是,我无法在official document中找到相关信息。那么,ng-submit的默认行为是什么?也就是说,我想知道在各种情况下哪些事件与“提交”相对应。在这个特定的例子中,“提交”是否意味着进入输入字段?

非常感谢。

回答

2

这是在你把作为链接的文档的顶部写:

启用角度表达结合的onsubmit事件。

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

在下面的评论,你认为:

当你点击提交按钮

这是不准确出现

onsubmit事件。

首先,让我们确定ngSubmit指令引发的事件。
angular-scenario.js,有这样的代码:

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

而且,如果你指的是HTML 2.0规范,对表单提交,(因此submit事件):

当有在一个表单中只有一个单行文本输入字段, 用户代理应接受该字段中的Enter作为请求提交 的表单。

此外,从角的代码,行15527(根据当前版本):当你点击提交按钮时

* 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`) 
+0

** **的onsubmit事件。但在这种情况下,只有一个输入文本字段。如何输入文字等于提交?这是官方在某种网络标准中规定的吗? – JBT

+0

@JBT答复已更新。 – Mik378

+1

很棒的回答!这正是我一直在寻找的。 – JBT