小编典典

AngularJS:表单验证和输入指令

angularjs

我在AngularJS应用程序中创建了一个指令,该指令在我的应用程序中生成样式输入。看起来像这样:

AC.directive('formInput',function ($compile) {
    return {
        transclude: true,
        replace: true,
        scope:{},
        templateUrl: '/views/partials/form/input.html',
        restrict: 'E',
        link: function(scope, element, attrs){

            scope.opts = attrs;

            if(attrs.ngModel){
                element.find('input').attr('ng-model', attrs.ngModel);
                $compile(element.contents())(scope.$parent);
            }

            if(!attrs.type){
                scope.opts.type = 'text';
            }
        }
    };
  }
)

它的模板是:

<label class="acxm-textfield {{opts.cssclass}}">
  <span ng-bind="opts.labeltext"></span>
  <input type="{{opts.type}}" name="{{opts.inputname}}" value="{{opts.inputvalue}}" placeholder="{{opts.placeholder}}" ng-maxlength="{{opts.maxLength}}"/>
</label>

调用很简单:

<form-input ng-model="UserProfile.FirstName" max-length="50" labeltext="{{'GENERAL.name' | translate}}" cssclass="acxm-p-horizontal" inputname="name" inputvalue="{{UserProfile.FirstName}}"></form-input>

我想为此字段创建验证,并添加了错误信息:

<span ng-show="showError(userInfoForm.name,'email')">
                    You must enter a valid email
</span>

而showError是:

$scope.showError = function(ngModelController, error) {

    return ngModelController.$error[error];
};

基本上,它是从《用AngularJS掌握Web应用程序开发》一书中复制的。我有一个问题,因为当我userInfoForm在控制台中登录表单时,我的名字是,{{opts.inputname}}而不是name属性,这里的值应该是“
name”。我究竟做错了什么?


阅读 217

收藏
2020-07-04

共1个答案

小编典典

dynamic-name在这里尝试我的指令:AngularJS动态表单字段验证

替换name="{{opts.inputname}}"dynamic-name="opts.inputname"

我还简化了演示代码:

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

表单输入模板:

<label class="acxm-textfield {{opts.cssclass}}">
  <span ng-bind="opts.labeltext"></span>
  <input type="{{opts.type}}" dynamic-name="opts.inputname" ng-model="opts.inputvalue"
  placeholder="{{opts.placeholder}}" 
  ng-maxlength="{{opts.maxLength}}" required/> //use dynamic-name directive to bind dynamic names.
</label>

DEMO(尝试清除文本以查看验证,我使用必需的验证进行快速演示,您可以将代码更改为电子邮件验证)。关键是使用dynamic- name指令。

2020-07-04