ng-enter 不调用任何函数

ng-enter with out calling any function

下面的代码是 todo-list 代码的一部分。

第一行是一个输入框,它的值可以通过newTodo访问。输入框用于输入新任务在待办事项列表中。

 <input class="todoField" id="newTodoField" type="text" ng-model="newTodo" placeholder="Add New Todo" ng-enter>
    <button id="todoSubmit" class="btn btn-default" ng-click="addTodo()">Add</button>

将新输入的任务名称提交给js有两种方式

1.输入任务名称后,只需单击添加按钮(该按钮位于第二行)code.which 正在调用 addTodo() js 函数,该函数负责将键入的文本添加到待办事项列表中。

2。在输入框中输入任务名称后,只需按回车键即可。

the doubt is with the second type method.Because the ng-enter does't call any function. It was just simply written in the end of tag.( If the code was like ng-enter="addTodo()" means i would have clearly understood)

And more over even if the ng-enter does't call any function the second method works nicely.How the ng-enter model supposed to call the addTodo() function.

完整代码在this_link中可用。 完整程序的演示在this_link

抱歉,如果问题很基础。

怀疑是第二种method.Because ng-enter 没有调用任何函数。它只是简单地写在标签的末尾。(如果代码像ng-enter="addTodo()"意味着我会清楚地理解)

坦率地说,angular 文档中没有关于 ng-enter 的文档,但您可以使用指令 ngEnter 使其工作,例如:

app.directive('ngEnter', function() {
    return function(scope, element, attrs) {
        element.bind("keydown", function(ev) {
            if(ev.which === 13) {
                scope.addTodo();
                ev.preventDefault();
            }
        });
    };
});

你不能在文本框上添加一个监听器吗?如图所示link:EventListener Enter Key

你可以得到这样的东西:

$(function(){
  document.querySelector('#newTodoField').addEventListener('keypress',function(e){
  var key = e.which || e.keyCode;
  if (key === 13) { // 13 is enter
   addTodo();
  }
 });
});