如何获得输入angularjs的最小值和最大值

时间:2014-11-24 21:06:34

标签: javascript angularjs

目前我正在使用自定义指令,该指令包含ng-minlength和ng-maxlength指令,以将这些指令的值应用于输入模型。我需要这样做,因为我正在创建一个验证服务,该服务使用表单上的角度$error对象来返回有关错误的用户友好消息。问题是,当涉及最小和最大长度时,我希望能够告诉用户长度应该是多少。我通过使用以下方法实现了这项工作

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

但这似乎有点长,可能难以维持和测试。有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

如果您只想告知用户最小值和最大值:

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

app.controller('MyCtrl',function($scope){
    $scope.minValue = 5;
    $scope.maxValue = 10;
});
&#13;
<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>
&#13;
&#13;
&#13;