【发布时间】:2014-09-30 01:36:34
【问题描述】:
我有一个带有两个输入控件的表单,每个控件都有不同的验证指令:
<input name='foo' id='foo' ng-model='foobar' validate-foo>
<input name='bar' id='bar' ng-model='foobar' validate-bar>
foo 的指令:
app.directive('validateFoo', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var id= attr.id;
if(viewValue.length > 0) {
console.log("*** foo is not empty");
}
else{
console.log("*** foo is empty");
}
});
}
}
});
bar 指令:
app.directive('validateBar', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var id= attr.id;
if(viewValue.length > 0) {
console.log("*** bar is not empty");
}
else{
console.log("*** bar is empty");
}
});
}
}
});
页面渲染时出现的错误如下:
Error: [$compile:ctreq] http://errors.angularjs.org/1.3.0-beta.5/$compile/ctreq?p0=ngModel&p1=valida
我不能在一个表单中有多个验证指令吗?
这是我执行动态 html 的指令,编译部分...
html= <input name=......, etc. etc.';
var dom= angular.element(html);
$element.append(dom);
$compile(dom)($scope);
【问题讨论】:
-
相同的代码,对我来说很好用.. plnkr.co/edit/fe9wqK?p=preview
Can i not have multiple directives for validation in one form- 是的,你可以。此外,在使用解析器时,您还需要返回视图值,以便在解析后分配该值。 -
thx...我会更新 Plunker 以更具体,我一定是遗漏了一些东西
-
我能看到的唯一区别是我正在从另一个指令动态生成 html。在该指令中,我添加了不同的验证器指令。当我只使用一个验证器指令时,一切都很好......你知道这是否会有所作为吗?
-
取决于您在该指令中执行的操作。没有看到就无法猜测......一个基本的事情是你需要
$compile它...... -
我发现了问题,我的动态版本中没有“ngModel”,d'uh...谢谢您的帮助...您为什么不提供答案,我会接受它
标签: angularjs angularjs-directive