防止控制器文本提交失败

Preventing Text Submission In Controller Failing

本文关键字:提交 失败 文本 控制器      更新时间:2023-09-26

我正在运行一个来自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>

My js file

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

$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 = '';
  }
};

您是否尝试过在输入中使用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/