【问题标题】:Preventing Text Submission In Controller Failing防止控制器中的文本提交失败
【发布时间】:2012-12-13 09:13:12
【问题描述】:

我正在 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 = '';
  }
};

【问题讨论】:

    标签: javascript html forms angularjs


    【解决方案1】:

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

    【讨论】:

    • 实际上,您的代码不起作用。我认为你的回答是有道理的,但现在我测试了它仍然表现相同。
    • $scope.todoText 声明为变量,然后在 if 语句中检查变量证明是徒劳的,因为错误仍然存​​在。我的代码已更新。
    • 在您的控制器中设置$scope.todoText = ''; 会将其初始化为空字符串。您应该在控制器中初始化模型,而不是在 addTodo 函数中。我在上面添加了一些代码
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 2012-06-25
      • 1970-01-01
      • 2020-01-16
      • 2012-02-19
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多