Mohammed Safeer Mohammed Safeer - 4 months ago 16
AngularJS Question

Hide error labels shown with angularjs form validation after some time

I am using angularjs form validation for client side validation. I need to hide the labels which displaying with angularjs error form validation method, after 3 seconds, after message appear.

Html will look like this,

<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>


Looking for a general solution like custom directives or else.

Thanks in Advance

Answer

I created a directive like this,

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);
                        }
                    });

                }
            };

        }
    };
});

and changed html to this,

<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 demo : https://plnkr.co/edit/P4uopx4MhOFEszXuuYyA?p=preview