Shawn Taylor
Shawn Taylor

Reputation: 1454

AngularJS ng:submit on 'enter' key

I'm trying to create a simple form that, upon hitting the 'enter' key, the entered data will be sent and appended to a list in my controller. The code I have is as follows:

controller.js

.controller('GenericTodosCtrl', function($scope) {

    $scope.todos=[];
    $scope.newTodo="";

    function addTodo() {
        alert("hello");
        $scope.todos.push({
            content: $scope.newTodo,
            done: false,
            editing: false
        });
        $scope.newTodo = "";
    };
});

main.html

<form ng:submit="addTodo()">
    <input name="newTodo" placeholder="Placeholder" type="text">
</form>

Currently, when I type in values and hit 'enter' nothing happens (not even the alert). I can't seem to figure out if I should be using "this" instead of $scope for things in controller.js. Does ng:submit require something in the ? Or is this an issue with my javascript instead?

Upvotes: 0

Views: 6070

Answers (1)

J.P.
J.P.

Reputation: 5745

You should make addTodo part of your $scope.

$scope.addTodo = function() {
    alert("hello");
    $scope.todos.push({
        content: $scope.newTodo,
        done: false,
        editing: false
    });
    $scope.newTodo = "";
};

Also, make sure the value in the input field is actually databound to your $scope value by using ngModel:

<form ng:submit="addTodo()">
    <input ng:model="newTodo" placeholder="Placeholder" type="text">
</form>

Upvotes: 4

Related Questions