我怎么可以强制的角度验证指令来运行? [英] How can I force an angular validation directive to run?
问题描述
我已经为我的表单验证指令。
它基本上验证了基于数据从另一个字段的字段值。
I've created a validation directive for my form. It basically validates a fields value based on data from another field.
它的工作原理完美: - )
It works perfect :-)
我的问题是,如果验证后,其他领域的变化被执行,验证将不再运行。
My problem is that if the other field changes after the validation was executed, the validation will not run again.
var myApp = angular.module('myApp', [])
.directive('validateInteger', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
var int1val = scope.int1;
scope.int2valid = (viewValue > int1val) ? "valid" : undefined;
if (scope.int2valid == "valid") {
ctrl.$setValidity('higher', true);
return viewValue;
} else {
ctrl.$setValidity('higher', false);
return undefined;
}
});
}
};
});
的jsfiddle: http://jsfiddle.net/hanspc/vCFFQ/
推荐答案
这是一个非常糟糕的主意,以明确提及你的指令某些领域。正如你所看到的,这有很多弊端:unportability,code重复,脆性大,...
It is a really bad idea to refer explicitly to some fields in your directive. As you can see, this has a lot of drawbacks : unportability, code repetition, brittleness, …
只要这样的事情:
<input type="text" ng-model="int2" validate-greater-integer="int1" />
和
myApp.directive('validateGreaterInteger', function() {
return {
require: 'ngModel',
scope: {
otherInteger : '=validateGreaterInteger',
}
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (viewValue > scope.otherInteger) {
ctrl.$setValidity('higher', true);
return viewValue;
} else {
ctrl.$setValidity('higher', false);
return undefined;
}
}
});
您可以再简单地做典型的状态控制(参见绑定形成并控制状态的为例)。
You can then simply do the typical state control (see the section "Binding to form and control state" for an exemple).
请注意,在这种情况下,也可以更简单地使用输入[号] 和分
参数。
Please notice that, in this case, you can also more simply use input[number] and its min
parameter.
在注释中讨论后编辑:
那么,在 NgModelController的功能。解析器
显然是被称为只有当模型变化的内容。你想要做的是使验证每当 INT1
或 INT2
的变化。因此,只要做到这一点:-):
Well, the functions in NgModelController.$parsers
are obviously called only when the content of the model changes. What you want to do is to make validation whenever int1
or int2
change. So just do it :-) :
link: function(scope, elm, attrs, ctrl) {
scope.$watch('data', function (data) {
if (data.int2 > data.int1) {
ctrl.$setValidity('higher', true);
return data.int2;
} else {
ctrl.$setValidity('higher', false);
return undefined;
}
}, true);
使用自己的验证变量( int2valid
在你的小提琴)也很奇怪。请使用典型的状态控制,具有类似 form.int2。$ error.higher
。
Use your own validation variable (int2valid
in your Fiddle) is also very strange. Please use the typical state control, with something like form.int2.$error.higher
.
这篇关于我怎么可以强制的角度验证指令来运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!