【问题标题】:Angularjs - how to get ng-message required error to display and disable input button at the same timeAngularjs - 如何获得 ng-message required 错误以同时显示和禁用输入按钮
【发布时间】:2015-07-06 01:12:42
【问题描述】:

如果用户单击没有内容的提交,我希望出现一条错误消息,并且我希望禁用提交按钮。 我可以让任何一个工作,但不能同时工作。

下面的代码显示消息,但允许一个空的待办事项。

<form name="todoForm" novalidate >


    <div ng-messages="todoForm.new.$error" ng-if="todoForm.$submitted"><div ng-message="required">Add Your Item Below...</div></div><!--message appears until valid input is entered--> 

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" >Add To List</button><!--disables form if form not valid-->

</form>

此版本禁用提交按钮但不弹出消息

<form name="todoForm" novalidate >


    <div ng-messages="todoForm.new.$error" ng-if="todoForm.$submitted"><div ng-message="required">Add Your Item Below...</div></div><!--message appears until valid input is entered--> 

    <input type="text" name="new" placeholder="start typing..." autofocus data-ng-model="newTodo" required=""/>

    <button input type="submit" ng-click="addTodo()" data-ng-disabled="todoForm.$invalid" >Add To List</button>
</form>

我想这是因为输入按钮被禁用时无法显示消息,因为没有提交任何内容?

我尝试使用 $disabled 和 $invalid 来代替,但它们没有奏效。

【问题讨论】:

  • 除非我遗漏了什么,否则我从中得到的是 ng-if="todoForm.$submitted"ng-messages="todoForm.new.$error" 冲突。即 ng-if 出现在同一个 div 上,我看不到 ng-message="required" 文本出现。当我删除 ng-if 时,显示所需的消息:plnkr.co/edit/8pE3jmBNYRpPSvyJA0ys?p=preview
  • 据我所知, ng-if="todoForm.$submitted" 与 data-ng-disabled="todo.Form.$invalid" 冲突。您的示例没有生成 ng 消息,那不是 html5 消息吗?

标签: angularjs forms message disabled-input


【解决方案1】:

我删除了 ng-message 元素上的冲突 ng-if。这是一个显示固定代码的工作 plunk。

http://plnkr.co/edit/gL0GoFT47mSeydKReLuD

我的假设是您忘记将“ngMessages”模块作为外部依赖注入。

你可以像这样修复你的代码:

var app = angular.module('plunker', ['ngMessages']);

【讨论】:

  • 谢谢,但我不希望在页面加载时出现消息,只是在用户不输入任何内容就提交时出现。我知道我有 ngMessage 工作,因为我可以让它工作,
  • 你可以使用 $dirty 来做到这一点,我已经更新了 plunk 以反映变化。
  • 如果用户没有输入任何内容,这将不起作用,只需点击提交即可。
  • 根据您在I want an error message to appear if the user clicks submit with no content 上方的帖子,这是一个示例 - plnkr.co/edit/8pE3jmBNYRpPSvyJA0ys?p=preview。然而,在我的示例中,提交按钮已启用(我删除了表单上的 novalidate 选项)。
  • @vtechmonkey 表单无效时按钮被禁用,我不明白您如何提交带有空白数据的表单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 2016-10-26
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
相关资源
最近更新 更多