角度setValidity不起作用?

时间:2014-03-29 03:48:35

标签: angularjs

我首先使用setValidity在Angular中制作指令。但不是我的预期,这是我的代码:

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

1 个答案:

答案 0 :(得分: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