如何将输入字段转换为可重用字段?

时间:2017-04-26 10:08:31

标签: angularjs forms directive

我输入了很多指令:

 <input class="form-control"
                                       mobile-number
                                       limit-characters
                                       number-only
                                       dir="ltr"
                                       ng-class="{'error-form-control': vm.form.step2.phoneNumber.$invalid && (vm.form.step2.phoneNumber.$dirty || vm.form.step2.phoneNumber.$touched)}"
                                       required
                                       ng-model="vm.formData.phoneNumber"
                                       name="phoneNumber"
                                       type="text">

如何将其变成可重复使用的指令,如下所示:

<phone-number ng-model="vm.formData.phoneNumber"></phone-number>

如何在此指令中使用角度形式验证?

1 个答案:

答案 0 :(得分:2)

我猜它看起来像这样

 app.directive('phoneNumber', function(){
       return {
          scope: {
             ngModel: '='
             classValidation: '=',
             inputName: '@'   
          },
          template: ' <input class="form-control" mobile-number limit-characters number-only dir="ltr" ng-class="classValidation" required ng-model="ngModel" name="{{inputName}}" type="text">',
          link: function(scope, elem, attr, ctrl) {

          }
       }
 })

HTML

 <phone-number ng-model="vm.formData.phoneNumber" input-name="phoneNumber" class-validation="{'error-form-control': vm.form.step2.phoneNumber.$invalid && (vm.form.step2.phoneNumber.$dirty || vm.form.step2.phoneNumber.$touched)}"></phone-number>