【问题标题】:Hide error labels shown with angularjs form validation after some time一段时间后隐藏带有 angularjs 表单验证的错误标签
【发布时间】:2016-02-25 17:01:18
【问题描述】:

我正在使用 angularjs 表单验证进行客户端验证。我需要隐藏使用 angularjs 错误表单验证方法显示的标签,3 秒后,消息出现后。

Html 会是这个样子,

<form name="userForm" novalidate>
  <div class="form-group">
    <label>Name</label>
    <input type="text" name="name" class="form-control" ng-model="name" required>
    <label ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</label>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="email" name="email" class="form-control" ng-model="email">
    <label ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</label>
  </div>
</form>

寻找通用解决方案,如自定义指令或其他。

提前致谢

【问题讨论】:

  • 那么在表单加载 3 秒后隐藏错误信息?还是出现的消息?还是别的什么?
  • 消息出现后
  • 我建议在 angularJS (docs.angularjs.org/api/ng/service/$timeout) 中使用 $timeout 函数,超时时间为 3 秒,然后使用 ng-show 或 ng-hide 隐藏标签。

标签: javascript angularjs validation angularjs-directive angularjs-validation


【解决方案1】:

我创建了一个这样的指令,

app.directive('timeoutHtml', function($timeout) {
    return {
        restrict: 'A',
        scope: {
            onVisible: '=showModel'
        },
        link: function(scope, element, attrs) {

            scope.$watch(function() {
                return attrs.ngShow;
            }, function(newValue, oldValue) {
                checkVisibility();
            });

            function checkVisibility() {
                if (element.is(':visible')) {
                    scope.$watch('onVisible', function(newValue, oldValue) {
                        console.log(newValue)
                        if (newValue === true) {
                            $timeout(function() {
                                scope.onVisible = false;
                            }, 2000);
                        }
                    });

                }
            };

        }
    };
});

把html改成这个,

<form name="userForm" novalidate="">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control" ng-model="name" required="" />
        <label  timeout-html="" show-model="submitted" ng-show="userForm.name.$invalid && submitted" class="help-block">You name is required.</label>
      </div>
      <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" class="form-control" ng-model="email" required />
        <label ng-show="userForm.email.$invalid && submitted" class="help-block">Enter a valid email.</label>
      </div>
      <button type="submit" ng-click="submitted=true;">Submit</button>
</form>

Plunker 演示:https://plnkr.co/edit/P4uopx4MhOFEszXuuYyA?p=preview

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多