如何在 angular 指令中动态注入验证属性

how to inject validation attributes dynamically inside angular directive

我正在使用 Angular 1.5.2,在 ng-messages 的顶部构建验证。基本上,应该是这样的,当然可以。

<form name="myform" class="form-horizontal">
    <h1>{{myform.name.$error}}!</h1>
    <input type="text" class="form-control" name="name" ng-model="name" required maxlength="3">
      <div ng-messages="myform.name.$error" role="alert">
        <div ng-message="maxlength">max length</div>
        <div ng-message="required">required</div>
      </div>
    </input>
  </form>

但是,我正在考虑一种动态注入验证规则和验证消息的方法,想法是我将创建一个指令(名为“​​validate”),指令应该添加必要的属性,如 "required"、"maxlength"、.... 并且还附加 ng-messages,就像这样

<form name="myform" class="form-horizontal">
    <h1>{{myform.name.$error}}!</h1>
    <input type="text" class="form-control" name="name" ng-model="name" validate />
  </form>

app.directive('validate', ['$compile', function ($compile) {
return {
    restrict: 'A',
    replace: false,
    compile: function(element, attrs) {
        element.removeAttr("ng-required");
        element.attr("ng-required", "true");

        element.removeAttr("maxlength");
        element.attr("maxlength", "3");

        var validationMessages = angular.element('<div ng-messages="myform.name.$error" role="alert"><div ng-message="maxlength">max length</div><div ng-message="required">required</div></div>');
        element.append(validationMessages)
    }
};}]);

我的指令不起作用,我看到已经添加了属性,还附加了 ng-messages,但是验证不起作用,我做错了什么?

我的笨蛋:https://plnkr.co/edit/GAd9UdcHxCDyV6dH1Q7e

https://plnkr.co/edit/wBPp6TamWtC6tDxwyDyz?p=preview

HTMl

 <form name="signupForm" ng-submit="vm.submit()" class="p-t-30">

                <div class="col-md-12 form-group fg-float p-0 m-t-5">
                    <div class="fg-line">
                        <input type="email" name="signupEmail" ng-model="vm.reqObj.user.personalEmailId" class="form-control" required="">
                    </div>
                    <label class="fg-label f-white">Email</label>
                    <div ng-show="signupForm.$submitted || signupForm.signupEmail.$touched" class="red">
                        <small ng-show="signupForm.signupEmail.$error.required" class="f-input-error f-700">Enter email</small> 
                        <small ng-show="signupForm.signupEmail.$error.email" class="f-input-error f-700">Enter valid email</small>
                    </div>
                </div>



                 <div class="clearfix"></div>
                <div class="col-md-12 form-group fg-float p-0 m-t-5">
                    <div class="fg-line">
                        <input type="password" name="password" class="form-control" ng-model="vm.reqObj.user.password" required="" />
                    </div>
                    <label class="fg-label f-white">Password</label>
                    <div ng-show="signupForm.$submitted || signupForm.password.$touched" class="red">
                        <small ng-show="signupForm.password.$error.required" class="f-input-error f-700">Enter password</small>
                    </div>
                </div>
                <div class="col-md-12 form-group fg-float p-0 m-t-5">
                    <div class="fg-line">
                        <input type="password" name="confirmPassword" class="form-control" ng-model="vm.reqObj.user.password1" required="" compare-to="vm.reqObj.user.password" />
                    </div>
                    <label class="fg-label f-white">Confirm Password</label>
                    <div ng-show="signupForm.$submitted || signupForm.confirmPassword.$touched" class="red">
                        <small ng-show="signupForm.confirmPassword.$error.required" class="f-input-error f-700">Enter confirm password</small> 
                        <small ng-show="signupForm.confirmPassword.$error.compareTo" class="f-input-error f-700">Password does not match</small>
                    </div>
                </div>
                <div class="text-left">
                    <span class="f-white f-300">By continuing, I agree to the 
                        <a class="f-white f-700">Seller Agreement</a> and <a class="f-white f-700">Privacy Policy</a>
                    </span>
                </div>
               <div class="text-center">
                     <button type="submit" class="btn login-btn" value="log in" ng-disabled="!signupForm.$valid"><span data-ng-if="vm.BtnTxt=='Signing up...'"><i class="glyphicon glyphicon-refresh spinning white f-s-16 l-h-0"></i>&nbsp;</span>colick</button>
                </div>
            </form>

和指令

app.directive('compareTo', function(){
           return {
             require: "ngModel",
             scope: {
               otherModelValue: "=compareTo"
             },
             link: function(scope, element, attributes, ngModel) {

               ngModel.$validators.compareTo = function(modelValue) {
                 return modelValue == scope.otherModelValue;


               };

               scope.$watch("otherModelValue", function() {
                 ngModel.$validate();
               });
             }
           };
   });

您好,请检查更新的答案,确切结果

script.js

 var myapp = angular.module("myapp", ['ngMessages']);

myapp.controller("mycontroller", ['$scope', function($scope){

}]);

myapp.directive('validate', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        require: "ngModel",
         scope: {
               otherModelValue: "= maxLength"
             },
        replace: false,
          link: function(scope, element, attributes, ngModel) {

               ngModel.$validators.maxLength = function(modelValue) {
                 if(modelValue.length > scope.otherModelValue)
                 {
                    console.log(modelValue.length == scope.otherModelValue)
                  return modelValue.length == scope.otherModelValue;
                 }



               };

               scope.$watch("otherModelValue", function() {
                 ngModel.$validate();
               });
             }

    };
}]);

和HTMl

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.angularjs.org/1.5.2/angular.js"></script>
  <script src="https://code.angularjs.org/1.5.2/angular-messages.js"></script>
  <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>

</head>

<body>
  <document ng-app="myapp">
    <div ng-controller="mycontroller">
      <form name="myform" class="form-horizontal">
        <input type="text" class="form-control" name="name" ng-model="name" required="" validate  max-length="3"/>

         <div ng-show="myform.$submitted || myform.name.$touched" class="red">
                        <small ng-show="myform.name.$error.required" class="f-input-error f-700">Enter confirm password</small> 
                        <small ng-show="myform.name.$error.maxLength" class="f-input-error f-700">Max length 3</small>
                    </div>
      </form>
    </div>
  </document>
</body>

</html>

和Css

/* Styles go here */
.f-input-error
{
  color:red;
}

我的新朋友希望这对您有所帮助https://plnkr.co/edit/YUwCvg6qr6M9mwAP3cqi?p=preview

您好,请根据您的要求查看

var myapp = angular.module("myapp", ['ngMessages']);

myapp.controller("mycontroller", ['$scope', function($scope){
  $scope.name = 'hello';
}]);

myapp.directive('validate', ['$compile', function ($compile) {
    return {
        restrict: 'A',
         require: "ngModel",
        scope: {
               otherModelValue: "=validate"
             },
        replace: false,
        link: function(scope, element, attributes, ngModel) {

               ngModel.$validators.validate = function(modelValue) {
                   element.removeAttr("ng-required");
                element.attr("ng-required", "true");

                element.removeAttr("maxlength");
                element.attr("maxlength", "3");

              if(element.attr("maxlength") ==  modelValue.length)
              {

                var tpl = '<div id="divID"  ng-show = true >Max Length 3</div>' ;
                var el = $compile(tpl)(scope);
                element.after(el);
              }
              else
              {
                var myEl = angular.element( document.querySelector( '#divID' ) );
               myEl.empty();
              }
                 return modelValue == scope.otherModelValue;


               };

               scope.$watch("otherModelValue", function() {
                 ngModel.$validate();
               });
             }


    };
}]);

和HTMl

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.angularjs.org/1.5.2/angular.js"></script>
  <script src="https://code.angularjs.org/1.5.2/angular-messages.js"></script>
  <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>

</head>

<body>
  <document ng-app="myapp">
    <div ng-controller="mycontroller">
      <form name="myform" class="form-horizontal">
        <h1>{{myform.name.$error}}!</h1>
        <input type="text" class="form-control" name="name" ng-model="name" validate />
      </form>
    </div>
  </document>
</body>

</html>