【发布时间】:2014-12-26 15:31:50
【问题描述】:
我正在尝试通过angularJS 根据其最小值和最大值验证一个数字
这是自定义指令,我首先尝试使用为输入数字验证提供 angularJs 的 max,它适用于静态数字而不是绑定数据。这就是我考虑自定义指令的原因
.directive('ngMax', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.ngMax, function(){
if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue);
});
var maxValidator = function(value) {
var max = scope.$eval(attr.ngMax) || Infinity;
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('ngMax', false);
return undefined;
} else {
ctrl.$setValidity('ngMax', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
};
});
在视图中:
<div class="modal-body" >
title: {{book.title}}<br>
price: {{book.price}}<br>
quantity: {{book.nbr_exemplaires}}
<form name= "myForm" ng-submit= "addToCart(book, quantity, <%= current_user.id %>)" novalidate >
<input type="number" min="1" ng-max="{{book.nbr_exemplaires}}" name= "quantite" ng-model="quantity" required >
<span style="color:red" ng-show="myForm.quantite.$error.required">
<span ng-show="myForm.quantite.$error.required">quantity is required!</span>
</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" ng-disabled="myForm.$invalid ">Save changes</button>
</div>
</form>
我不明白问题出在哪里
【问题讨论】:
-
我会警告您不要使用“NG”前缀:如果您必须升级到 angularJS 10.7,谁会知道他们是否会实施 ngMax 指令?在这种情况下你会遇到一些错误..
标签: angularjs angularjs-directive