如何在angular指令

时间:2016-06-08 09:10:09

标签: angularjs 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>

但是,我正在考虑一种动态注入验证规则和验证消息的方法,我的想法是创建一个指令(名为&#34; 验证&#34;),该指令应该添加必要的属性,例如&#34; required&#34;,&#34; maxlength&#34;,....并且还附加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

3 个答案:

答案 0 :(得分:0)

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();
               });
             }
           };
   });

答案 1 :(得分:0)

嗨,请查看更新的答案,确切的结果

的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

答案 2 :(得分:0)

您好请根据您的要求进行检查

let cameraInput = try AVCaptureDeviceInput(device: self.backCameraDevice)
            do {
                try cameraInput.device.lockForConfiguration()

                if cameraInput.device.isExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure) {
                    cameraInput.device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
                }

                if cameraInput.device.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) {
                    cameraInput.device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
                }


                // CRASH HERE
                self.backCameraDevice.flashMode = .Off


                cameraInput.device.unlockForConfiguration()
            } catch {
            }

和HTMl

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();
               });
             }


    };
}]);