Angularjs :显示消息



我尝试在密码不匹配时显示消息但不显示任何想法 ?我尝试在密码不匹配时显示消息但不显示任何想法?

命令:

angular.module('crud')
  .directive('equal', function () {
    return {
      require: 'ngModel',
      scope: {
        equal: '='
      },
      link: function(scope, elem, attrs, ctrl) {
        ctrl.$validators.equal = function(modelValue, viewValue) {
          return modelValue === scope.equal;
        };
        scope.$watch('equal', function(newVal, oldVal) {
          ctrl.$validate();
        });
      }
    };
  });

.html

<form name="userForm"  ng-submit="signup()" class="form-horizontal" role="form" >
    <input type="password" class="form-control ng-invalid submitted" id="password" name="password" ng-model="password" ng-minlength="8" ng-maxlength="20"  required />
     <input type="password" equal="password" class="form-control  ng-invalid submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required  />
    <span  ng-show="userForm.password.$error.equal && userForm.password.$dirty">Passwords don't match.</span>
</form>

一切都很好,只有一个例外,您应该在密码输入上添加相等指令,因为您正在显示密码错误,因此您应该验证密码。除此之外还可以。尽管您可以考虑使用 ng-messages 来显示错误。

angular.module('crud', ['ngMessages']);
angular.module('crud')
  .directive('equal', function () {
    return {
      require: 'ngModel',
      scope: {
        equal: '='
      },
      link: function(scope, elem, attrs, ctrl) {
        ctrl.$validators.equal = function(modelValue, viewValue) {
          return modelValue === scope.equal;
        };
        scope.$watch('equal', function(newVal, oldVal) {
          ctrl.$validate();
        });
      }
    };
  });
.valid {
  border: 1px solid green;
}
.invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script src="https://code.angularjs.org/1.5.5/angular-messages.js"></script>
<div ng-app="crud">
<form name="userForm"  class="form-horizontal" role="form" >
    <input type="password" class="form-control ng-invalid submitted" id="password" name="password" equal="confirmPassword" ng-model="password" ng-minlength="8" ng-maxlength="20" ng-class="{'valid':  userForm.password.$valid || !userForm.password.$dirty, 'invalid': userForm.password.$invalid && userForm.password.$dirty}"  required />
     <input type="password"  class="form-control submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required  />
    <div ng-messages="userForm.password.$error" ng-show="userForm.password.$dirty" role="alert">
      <div ng-message="required">Please enter a value for this field.</div>
      <div ng-message="equal">Passwords don't match.</div>
    </div>
  
</form>
</div>

相关内容

  • 没有找到相关文章

最新更新