I'm running a simple example from the main page of Angular involving a todo list. I want to prevent the user from submitting a todo when the input field is blank. The problem is when I load the page and the first thing I do is I click inside the input field and press enter, then the blank todo is added the Todo list. However, after that the validation works. I know there are other ways of doing this, but I want to know why this bug exists and how to fix it.
My html below
<form ng-submit="addTodo()">
<input ng-model="todoText" placeholder="Add a todo here" type="text" />
<input class="button" type="submit" value="add">
</form>
My js file
$scope.addTodo = function() {
var text = $scope.todoText;
if (text != "") {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
}
};
$scope.todoText
is undefined
, so it passes your condition and then is set to empty string ''
, based on your model's variables
either do if (!$scope.todoText) {
or initialize it to empty string $scope.todoText = '';
in controller:
$scope.todoText = '';
$scope.addTodo = function() {
if ($scope.todoText != "") {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
}
};
Have you tried using the required
attribute in the input?
<input type="text"
ng-model="todoText"
required <------------- prevents submission and marks the view as invalid
size="30"
placeholder="add new todo here" />
Have a try at http://jsfiddle.net/hbulhoes/uBXfN/