han*_*sch 5 validation angularjs
我已经为我的表单创建了一个验证指令.它基本上根据来自另一个字段的数据验证字段值.
它完美无缺:-)
我的问题是,如果在执行验证后其他字段发生更改,则验证将不再运行.
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;
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
jsfiddle:http://jsfiddle.net/hanspc/vCFFQ/
在指令中明确引用某些字段是一个非常糟糕的主意。正如你所看到的,这有很多缺点:不可移植性、代码重复、脆弱性、\xe2\x80\xa6
\n\n就做这样的事情:
\n\n<input type="text" ng-model="int2" validate-greater-integer="int1" />\nRun Code Online (Sandbox Code Playgroud)\n\n和 :
\n\nmyApp.directive(\'validateGreaterInteger\', function() {\n return {\n require: \'ngModel\',\n scope: {\n otherInteger : \'=validateGreaterInteger\',\n }\n link: function(scope, elm, attrs, ctrl) {\n ctrl.$parsers.unshift(function(viewValue) {\n if (viewValue > scope.otherInteger) {\n ctrl.$setValidity(\'higher\', true);\n return viewValue;\n } else {\n ctrl.$setValidity(\'higher\', false);\n return undefined;\n }\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n\n然后,您可以简单地执行典型的状态控制(有关示例,请参阅“绑定到表单和控制状态”部分)。
\n\n请注意,在这种情况下,您还可以更简单地使用input[number]及其min参数。
在评论中讨论后编辑:
\n\nNgModelController.$parsers嗯,显然只有当模型的内容发生变化时才会调用 中的函数。你想要做的是每当int1或int2改变时进行验证。所以就这样做吧:-):
link: function(scope, elm, attrs, ctrl) {\n scope.$watch(\'data\', function (data) {\n if (data.int2 > data.int1) {\n ctrl.$setValidity(\'higher\', true);\n return data.int2;\n } else {\n ctrl.$setValidity(\'higher\', false);\n return undefined;\n }\n }, true);\nRun Code Online (Sandbox Code Playgroud)\n\n使用你自己的验证变量(int2valid在你的小提琴中)也很奇怪。请使用典型的状态控制,例如form.int2.$error.higher.
| 归档时间: |
|
| 查看次数: |
10291 次 |
| 最近记录: |