Search code examples
javascriptjqueryhtmlangularjsangular-ngmodel

ng-enter with out calling any function


The below code is a part of a todo-list code.

The first line is a input box where its value is accessible through newTodo.The input box is used to type the new task in the todo-list.

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

There is two way to submit the newly typed task name to js.

1.after typing the task name just by clicking the add button(the button is in the second line) of the code.which is calling addTodo() js function which does the job of adding the typed text in the todo-list.

2.after typing the task name just pressing enter button with in the input box.

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.

The complete code is available in this_link. The demo of the complete program is available in this_link

sorry if the question is very basic.


Solution

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

    Frankly speaking there is no documentation about ng-enter at angular docs but you can make it work with using a directive ngEnter like:

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