目前,我正在使用一个自定义指令,该指令包装了 ng-minlength 和 ng-maxlength 指令,以将这些指令的值应用到输入模型。我需要这样做,因为我正在创建一个验证服务,该服务使用表单上的 Angular $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'];
}
}
}
}
}
}])
但这似乎有点狭隘,并且可能难以维护和测试。有更好的方法吗?
最佳答案
如果您只想告知用户最小值和最大值:
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>
关于javascript - 如何获取输入 angularjs 的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114170/