gpt4 book ai didi

javascript - 防止 Controller 中的文本提交失败

转载 作者:行者123 更新时间:2023-11-30 18:13:12 24 4
gpt4 key购买 nike

我正在运行一个来自 Angular 主页的简单示例,其中涉及待办事项列表。我想阻止用户在输入字段为空白时提交待办事项。问题是当我加载页面时,我做的第一件事是在输入字段内单击并按回车键,然后将空白待办事项添加到待办事项列表中。但是,之后验证有效。我知道还有其他方法可以做到这一点,但我想知道为什么存在这个错误以及如何修复它。

下面是我的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 = '';
}
};

最佳答案

$scope.todoTextundefined ,因此它通过了您的条件,然后根据您的模型设置为空字符串 ''变量

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

在 Controller 中:

$scope.todoText = '';

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

关于javascript - 防止 Controller 中的文本提交失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com