假设我有以下(非常简单的)数据结构:
$scope.accounts = [{
percent: 30,
name: "Checking"},
{ percent: 70,
name: "Savings"}];
然后我将以下结构作为表单的一部分:
<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 中有相当多的解决方案,但我一直无法找到 Angular 的良好来源。
编辑:我想出了以下自定义指令(“share”是原始代码“percent”的同义词)。share-validate 指令将表单的映射"{group: accounts, id: $index}"
作为其值。
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;
});
}
};
});
这几乎可以工作,但不能处理一个字段无效的情况,但另一个字段的后续更改使其再次有效。例如:
Field 1: 61
Field 2: 52
如果我将字段 2 降低到 39,字段 2 现在将有效,但字段 1 仍然无效。想法?