4

我正在使用angularjs表單驗證客戶端驗證。我需要在出現消息後3秒鐘後隱藏使用angularjs錯誤表單驗證方法顯示的標籤。隱藏錯誤標籤顯示與angularjs形式驗證一段時間後

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> 

尋找像自定義指令或者其他的通用解決方案。

由於提前

+0

所以隱藏錯誤信息表單加載3秒後?或消息的出現?或者是其他東西? – ryanyuyu

+1

消息出現後 –

+0

我建議在超時時間爲3秒的angularJS(https://docs.angularjs.org/api/ng/service/$timeout)中使用$ timeout函數,然後使用ng-show或ng隱藏標籤-隱藏。 –

回答

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

相關問題