2014-11-24 133 views
0

當前我正在使用一個自定義指令,它包裝ng-minlength和ng-maxlength指令以將這些指令的值應用於輸入模型。我需要這樣做,因爲我正在創建一個驗證服務,該服務使用表單上的角度爲$error的對象返回關於錯誤的用戶友好消息。問題是,當涉及到最小和最大長度時,我希望能夠告訴用戶長度應該是多少。我通過使用以下方法得到了這個工作如何獲取輸入的最小值和最大值angularjs

directive('minlength', ['$compile', function ($compile) { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     compile: function compile(tElement) { 
      tElement.attr('ng-minlength', tElement.attr('minlength')); 
      tElement.removeAttr('minlength'); 
      return { 
       post: function postLink(scope, elem, attrs) { 
        var keys, 
         form, 
         field = attrs['ngModel']; 
        $compile(elem)(scope); 
        for (keys in scope) { 
         if (scope.hasOwnProperty(keys)) { 
          if (keys.substring(0, 2).indexOf('$') < 0) { 
           if (keys !== 'this') { 
            form = keys; 
            break; 
           } 
          } 
         } 
        } 
        if (form) { 
         console.log(attrs); 
         scope[form][field]['minlength'] = attrs['minlength']; 
        } 
       } 
      } 
     } 
    } 
}]) 

但是,這似乎有點冗長,可能難以維護和測試。有一個更好的方法嗎?

+0

這個怎麼樣http://jsfiddle.net/uf0bt8vL/ – 2014-11-24 21:39:46

+0

我不確定爲什麼你不能使用[現有的ng-minlength和ng-maxlength](https://docs.angularjs.org/api/ng/directive/input)。我看到@Avraam似乎同意。有沒有理由不起作用? – 2014-11-24 21:42:53

+0

這個應用程序是添加到另一個應用程序,爲用戶提供一個Web界面來提交請求。我不能只使用ng-minlength的原因是因爲我的應用程序的用戶將創建自定義最小和最大長度的自定義窗體,所以我不能假設我會知道它是什麼並且靜態地輸入它 – richbai90 2014-11-24 21:55:13

回答

2

如果你想只是爲了告知用戶的最小值和最大值:

var app = angular.module('myApp',[]); 
 

 
app.controller('MyCtrl',function($scope){ 
 
    $scope.minValue = 5; 
 
    $scope.maxValue = 10; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
<div ng-controller="MyCtrl"> 
 
<form name="myForm"> 
 
    Last name: <input type="text" name="lastName" ng-model="user.last" 
 
     ng-minlength="{{minValue}}" ng-maxlength="{{maxValue}}"> 
 
    <span class="error" ng-show="myForm.lastName.$error.minlength"> 
 
     Should be {{minValue}} charachters long</span> 
 
    <span class="error" ng-show="myForm.lastName.$error.maxlength"> 
 
     No more than {{maxValue}} characters please</span><br> 
 
    </form> 
 
</div> 
 
</div>

+0

問題與這個方法是假設我知道最小和最大長度是多少。在應用程序的最終版本中,客戶將被允許更改這些值,因爲他們將使用此應用程序作爲其客戶的前端 – richbai90 2014-11-24 21:57:46

+0

@ richbai90,您可以使用您的控制器將該值插入到我認爲的表單中。我會更新我的答案,並讓我們看看它是否是你需要的。 – 2014-11-24 22:00:39

+0

@ richbai90我更新了我的答案,我不確定客戶將如何更改最小值和最大值,但對於控制器,我認爲您具有這種靈活性(或者更好地使用控制器中注入的服務) – 2014-11-24 22:04:39

相關問題