角度:验证多个相关领域 [英] angular: Validate multiple dependent fields
问题描述
比方说,我有以下的(很简单)数据结构:
Let's say I have the following (very simple) data structure:
$scope.accounts = [{
percent: 30,
name: "Checking"},
{ percent: 70,
name: "Savings"}];
然后,我有以下结构的一种形式的一部分:
Then I have the following structure as part of a form:
<div ng-repeat="account in accounts">
<input type="number" max="100" min="0" ng-model="account.percent" />
<input type="text" ng-model="account.name" />
</div>
现在,我想的百分比之和验证,以100为每个组帐户,但大部分我见过的自定义指令的例子只处理验证的个人价值。什么是创建一个指令,将在一次验证多个相关字段的惯用方式是什么?有jQuery的。这个解决方案相当数量的,但我一直没能找到角度的良好来源。
Now, I want to validate that the percents sum to 100 for each set of accounts, but most of the examples I have seen of custom directives only deal with validating an individual value. What is an idiomatic way to create a directive that would validate multiple dependent fields at once? There are a fair amount of solutions for this in jquery, but I haven't been able to find a good source for Angular.
编辑:我想出了以下自定义指令(共享是原来的code的百分比的代名词)。
股权分验证指令采用地图的形式的{组:帐号,ID:$指数}。
作为其值
I came up with the following custom directive ("share" is a synonym for the original code's "percent").
The share-validate directive takes a map of the form "{group: accounts, id: $index}"
as its value.
app.directive('shareValidate', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
params = angular.copy(scope.$eval(attr.shareValidate));
params.group.splice(params.id, 1);
var sum = +viewValue;
angular.forEach(params.group, function(entity, index) {
sum += +(entity.share);
});
ctrl.$setValidity('share', sum === 100);
return viewValue;
});
}
};
});
这个概工作,但不能处理其中一个字段是无效的情况下,但在另一场后续变化使得它再次有效。例如:
This ALMOST works, but can't handle the case in which a field is invalidated, but a subsequent change in another field makes it valid again. For example:
Field 1: 61
Field 2: 52
如果我走场2下降到39,2场现在是有效的,但场1仍然无效。想法?
If I take Field 2 down to 39, Field 2 will now be valid, but Field 1 is still invalid. Ideas?
推荐答案
好吧,下面的工作(同样,共享是百分比):
Ok, the following works (again, "share" is "percent"):
app.directive('shareValidate', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.shareValidate, function(newArr, oldArr) {
var sum = 0;
angular.forEach(newArr, function(entity, i) {
sum += entity.share;
});
if (sum === 100) {
ctrl.$setValidity('share', true);
scope.path.offers.invalidShares = false;
}
else {
ctrl.$setValidity('share', false);
scope.path.offers.invalidShares = true;
}
}, true); //enable deep dirty checking
}
};
});
在HTML中,设置属性为共享验证和价值给你想要观看的一组对象。
In the HTML, set the attribute as "share-validate", and the value to the set of objects you want to watch.
这篇关于角度:验证多个相关领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!