2014-03-29 47 views
1
我第一次使用 setValidity,以使Angular.but一個指令

還不如我預期的,這裏是我的代碼:Angular setValidity不起作用?

angular.module('myApp', []) 
.controller('ctrl',function($scope){ 
    $scope.pw=''; 
}) 
.directive('pwCheck', function(){ 
    return { 
    require: 'ngModel', 
    link: function (scope, elem, attrs, ctrl) { 
    elem.on('keyup', function() { 
     scope.$apply(function() { 
     var len = elem.val().length; 

      if(len===0){ 
       ctrl.$setValidity('zero',true); 
      } else if(len>1 && len<6){ 
       ctrl.$setValidity('one',true); 
      } else { 
        ctrl.$setValidity('two',true); 
      } 

     }); 
     }); 
    } 
    }; 
}); 

HTML:

<body ng-controller="ctrl"> 
    <form id="myForm" name="myForm"> 
    <input type="text" ng-model="pw" pw-check /> 

    {{myForm.$error}} 
    <div class="msg-block" ng-show="myForm.$error"> 
     <span class="msg-error" ng-show="myForm.pw.$error.zero"> 
      Input a password. 
     </span> 
     <span class="msg-error" ng-show="myForm.pw.$error.one"> 
      Passwords too short. 
     </span> 
     <span class="msg-error" ng-show="myForm.pw.$error.two"> 
      Great. 
     </span> 
    </div> 
    </form> 
</body> 

在線演示:

http://jsbin.com/cefecicu/1/edit

回答

4

我認爲你需要:

//Reset your validity 
    ctrl.$setValidity('zero',true); 
    ctrl.$setValidity('one',true); 
    ctrl.$setValidity('two',true); 
    if(len===0){ 
      ctrl.$setValidity('zero',false); 
     } else if(len>=1 && len<6){ //use len>=1 instead 
      ctrl.$setValidity('one',false); 
     } else { 
      ctrl.$setValidity('two',false); 
     } 

使用false指示錯誤(無效):

,並給予名稱,您輸入:

<input type="text" ng-model="pw" name="pw" pw-check /> 

http://jsbin.com/cefecicu/11/edit

+0

仍然沒有工作,沒有顯示消息。 –

+0

@Ryan Yiada:查看更新後的答案 –