2012-12-28 13 views
1

我正在运行一个简单的示例,其中包含待办事项列表的Angular主页。我想阻止用户在输入字段为空时提交待办事项。问题是当我加载页面时,我所做的第一件事是在输入字段内单击并按Enter键,然后将空白待办事项添加到待办事项列表中。但是,之后验证工作。我知道还有其他方法可以做到这一点,但我想知道为什么存在这个错误以及如何解决这个问题。防止控制器故障中的文本提交

我的HTML下面

<form ng-submit="addTodo()"> 
    <input ng-model="todoText" placeholder="Add a todo here" type="text" /> 
    <input class="button" type="submit" value="add"> 
</form> 

我的js文件

$scope.addTodo = function() { 
    var text = $scope.todoText; 
    if (text != "") { 
    $scope.todos.push({text:$scope.todoText, done:false}); 
    $scope.todoText = ''; 
    } 
}; 

回答

2

$scope.todoTextundefined,所以它通过您的病情,然后设置为空字符串'',基于模型的变量

要么if (!$scope.todoText) {要么将​​其初始化为空字符串$scope.todoText = '';

在控制器:

$scope.todoText = ''; 

$scope.addTodo = function() { 
    if ($scope.todoText != "") { 
    $scope.todos.push({text:$scope.todoText, done:false}); 
    $scope.todoText = ''; 
    } 
}; 
+0

一试其实,你的代码不起作用。我认为你的回答是有道理的,但现在我测试了它仍然是一样的。 – jason328

+0

声明'$ scope.todoText'作为变量,然后检查if语句中的变量被证明是徒劳的,因为错误依然存在。我的代码已更新。 – jason328

+0

设置'$ scope.todoText ='';'在你的控制器中将它初始化为空字符串。您应该在控制器中初始化您的模型,而不是在addTodo函数中。我在 –

0

您是否尝试过在输入使用required属性?

<input type="text" 
     ng-model="todoText" 
     required <------------- prevents submission and marks the view as invalid 
     size="30" 
     placeholder="add new todo here" /> 

有在http://jsfiddle.net/hbulhoes/uBXfN/