我是一个有角度的新手,我在角度验证形式验证指令的工作方式上遇到了麻烦。
我知道我可以很容易地将指令添加到各个字段,但是我试图添加一个验证,该验证将比较两个表单字段(这两个字段都是模型的元素)。
这是一个表单框架:
<form name="edit_form" >
<input name="min" type="number" ng-model="field.min"/>
<input name="max" type="number" ng-model="field.max"/>
</form>
<div class="error" ng-show="edit_form.min.$dirty || edit_form.max.$dirty">
<small class="error" ng-show="(what goes here?)">
Min cannot exceed max
</small>
</div>
简而言之,我想编写一条指令,并使用它来显示/隐藏small.error
ifmin
和max
都有值but min > max
。如何在一个指令中访问两个字段?指令是这项工作的正确工具吗?
剥皮猫的方法很多。
app.directive('lowerThan', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.lowerThan;
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('lowerThan', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) < parseInt(comparisonModel, 10) );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('lowerThan', function(comparisonModel){
// Whenever the comparison model changes we'll re-validate
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
用法:
<input name="min" type="number" ng-model="field.min" lower-than="{{field.max}}" />
<span class="error" ng-show="form.min.$error.lowerThan">
Min cannot exceed max.
</span>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句