加入收藏 | 设为首页 | 会员中心 | 我要投稿 拼字网 - 核心网 (https://www.hexinwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

表单 – 在Angularjs中禁用按钮时如何允许ng-click

发布时间:2020-12-31 04:25:22 所属栏目:资源 来源:网络整理
导读:我有以下表格: form name="formuser" action='/signup' method='post' novalidate input type="text" name="firstname" ng-model="firstname" ng-class="{ 'has-error' : (formuser.firstname.$invalid !formuser.firstname.$pristine) || hasSubmitted}" r

我有以下表格:

<form name="formuser" action='/signup' method='post' novalidate>

    <input type="text" name="firstname" ng-model="firstname" ng-class="{ 'has-error' : (formuser.firstname.$invalid && !formuser.firstname.$pristine) || hasSubmitted}" required />

    <button type="submit" ng-disabled="formuser.$invalid" ng-click="hasSubmitted=true">Submit</button>
</form>

我正在尝试将输入字段中的“has-error”类添加到用户输入内容之后无效,或者在输入仍处于原始状态时点击提交按钮.我已将ng-disabled添加到提交按钮以禁用表单子目录,但我仍然希望触发ng-click以更改hasSubmitted范围.问题是按钮上的ng-disable也禁用了ng-click.

我知道我总是可以在表单上使用ng-submit,在我的控制器中进行验证,然后启动ajax请求,但我的身份验证框架要求我实际提交表单并重定向浏览器.

解决方法

好吧,而不是制造黑客,最干净的解决方案是启用按钮,只需使用简单的指令处理提交:
angular.module('common',[]).directive('preventSubmit',function () {
    return {
        restrict: 'A',scope: {
            preventSubmit: '='
        },link: function (scope,element) {
            element.bind('submit',function(e) {
                if (scope.preventSubmit) {
                    e.preventDefault();
                }
            });
        }
    }
});

所以它做什么它绑定到提交事件,如果表单无效,它会阻止表单提交.如果你不使用动作属性,Angular会自动处理它,你可以处理它,但是如果指定了动作并且正常提交,这个指令可能非常有用.

并在标记中:

<form name="formuser" action='/signup' method='post' 
      novalidate prevent-submit="formuser.$invalid">
  ...
  <button type="submit" ng-click="hasSubmitted=true">Submit</button>
</form>

使用ng-style或ng-class,您可以根据表单状态按预期设置按钮的样式.

(编辑:拼字网 - 核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读