Angularjs: 表单验证和输入指令

5

我在一个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”。我做错了什么?


请看我在这里对类似问题的回答:https://dev59.com/52Ei5IYBdhLWcg3wPaZh#21457121 - Khanh TO
将指令声明为我发布的链接中的方式,并将 name="{{opts.inputname}}" 替换为 dynamic-name="opts.inputname" - Khanh TO
Khanh,是的,我可以创建一个指令,但由于我的输入已经是一个指令,所以我只添加了:element.find('input').attr('name', scope.opts.inputname); 它会添加一个名称属性,但我仍然无法使我的验证工作:/ 在 showError 中,当我尝试访问我的字段时,ngModelController 仍然未定义...这是一个例子:http://plnkr.co/edit/xKktbdw1dP5elWKnmQMC?p=preview - Adrian Wajs
是的,我认为你的评论很好... 嗯,但如何使其工作呢 :) - Adrian Wajs
我发现我的解决方案可行,只是忘记在输入字段中加上“required”。我太傻了。我已经发布了答案,请看一下。 - Khanh TO
2个回答

9

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

dynamic-name="opts.inputname"替换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>

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


Khanh,感谢你的帮助,你的示例很有效!:) 我认为主要问题是我的指令使用了value和ng-model :) 因为你的指令没有使用它们 :) - Adrian Wajs

0

这里是关于表单/名称验证指令的另一种方法stacklink

<form name="myFormName">
  <nested directives of many levels>
  ex: <input ng-repeat=(index, variable) in variables" type="text"
             my-name="{{ variable.name + '/' + 'myFormName' }}"
             ng-model="variable.name" required />
  ex: <select ng-model="variable.name" ng-options="label in label in {{ variable.options }}"
             my-name="{{ variable.name + '/' + 'myFormName' }}"
      </select>
</form

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

app.directive('rsName', function(){

  var rsNameError = "rsName directive error: "

  return {
    restrict:'A', // Declares an Attributes Directive.
    require: 'ngModel', // ngModelController.

    link: function( scope, elem, attrs, ngModel ){
      if( !ngModel ){ return } // no ngModel exists for this element

      // check rsName input for proper formatting ex. something/something
      checkInputFormat(attrs);

      var inputName = attrs.rsName.match('^\\w+').pop(); // match upto '/'
      assignInputNameToInputModel(inputName, ngModel);

      var formName = attrs.rsName.match('\\w+$').pop(); // match after '/'
      findForm(formName, ngModel, scope);
    } // end link
  } // end return

  function checkInputFormat(attrs){
    if( !/\w\/\w/.test(attrs.rsName )){
      throw rsNameError + "Formatting should be \"inputName/formName\" but is " + attrs.rsName
    }
  }

  function assignInputNameToInputModel(inputName, ngModel){
    ngModel.$name = inputName
  }

  function addInputNameToForm(formName, ngModel, scope){
    scope[formName][ngModel.$name] = ngModel; return
  }

  function findForm(formName, ngModel, scope){
    if( !scope ){ // ran out of scope before finding scope[formName]
      throw rsNameError + "<Form> element named " + formName + " could not be found."
    }

    if( formName in scope){ // found scope[formName]
      addInputNameToForm(formName, ngModel, scope)
      return
    }
    findForm(formName, ngModel, scope.$parent) // recursively search through $parent scopes
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接