Angularjs: form validation and input directive

后端 未结 2 664
情话喂你
情话喂你 2020-12-09 23:14

I created a directive in an AngularJS app which produces styled input in my application. It looks like this:

AC.directive(\'formInput\',function ($compile) {         


        
2条回答
  •  借酒劲吻你
    2020-12-09 23:58

    Try my dynamic-name directive here: AngularJS dynamic form field validation

    Replace name="{{opts.inputname}}" with dynamic-name="opts.inputname"

    I also simplified your code for demonstration:

    app.directive("dynamicName", function($compile) {
      return {
        restrict: "A",
        terminal: true,
        priority: 1000,
        link: function(scope, element, attrs) {
          var name = scope.$eval(attrs.dynamicName);
          if (name) {
            element.attr('name', name);
            element.removeAttr("dynamic-name");
            $compile(element)(scope);
          }
        }
      };
    });
    
    app.directive('formInput', function($compile) {
      return {
        replace: true,
        scope: {},
        templateUrl: 'formInput.html',
        restrict: 'E',
        link: function(scope, element, attrs) {
          scope.opts = attrs;
    
    
          $compile(element.contents())(scope);
        }
      }
    });
    

    Form Input template:

    
    

    DEMO (try clearing the text to see the validation, I used required validation for quick demonstration, you could change the code to email validation). The key is using the dynamic-name directive.

提交回复
热议问题