我有一个用于表单验证的模块validationMod,它有两个自定义指令。但是,当我运行程序时,只有第二个指令执行并警告test2。当我删除第二个指令时。自定义指令customValidation
开始解决原因。
angular.module('validationMod', ['ngMessages']).directive('customValidation', function () {
alert('test');
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
function validationError(value) {
if (/[a-zA-z]/.test(value)) {
ctrl.$setValidity('invalid', true);
} else {
ctrl.$setValidity('invalid', false)
}
if (/[0-9]/.test(value)) {
ctrl.$setValidity('invalid', false)
} else {
ctrl.$setValidity('invalid', true)
}
return value;
}
ctrl.$parsers.push(validationError);
}
};
});
angular.module('validationMod', ['ngMessages']).directive('validatetest', function () {
alert('test2');
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
function validateEmail(value) {
if (/[a-zA-Z]/.test(value)) {
ctrl.$setValidity('test', true);
}
else {
ctrl.$setValidity('test', false);
}
return value;
}
ctrl.$parsers.push(validateEmail);
}
};
});
angular.module('myApp', ['validationMod']);
这是我的表格
<form name="myform" novalidate>
<table>
<tr>
<td>First name :<input name='firstName' type='text' required ng-model='name' custom-validation></td>
<td ng-messages="myform.firstName.$error"><span ng-message="invalid">invalid</span></td>
</tr>
<tr>
<td>Last name :<input name='lastName' type='text' required ng-model='lstname' custom-validation></td>
<td ng-messages="myform.lastName.$error"><span ng-message="invalid">invalid</span></td>
</tr>
<tr>
<td>Email :<input type="text" ng-model="email" required name="email" validatetest /></td>
<td ng-messages="myform.email.$error"><span ng-message="test"> email id required</span></td>
</tr>
</table>
</form>
我们如何为同一模块使用多个自定义指令。
答案 0 :(得分:1)
您已重新初始化模块&#34; validationMod&#34;。只需尝试以下方式:
var validationModule = angular.module('validationMod', ['ngMessages']).directive('customValidation', function () {
alert('test');
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ctrl) {
function validationError(value) {
if (/[a-zA-z]/.test(value)) {
ctrl.$setValidity('invalid', true);
} else {
ctrl.$setValidity('invalid', false)
}
if (/[0-9]/.test(value)) {
ctrl.$setValidity('invalid', false)
} else {
ctrl.$setValidity('invalid', true)
}
return value;
}
ctrl.$parsers.push(validationError);
}
};
});
validationModule.directive('validatetest', function () {
alert('test2');
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
function validateEmail(value) {
if (/[a-zA-Z]/.test(value)) {
ctrl.$setValidity('test', true);
}
else {
ctrl.$setValidity('test', false);
}
return value;
}
ctrl.$parsers.push(validateEmail);
}
};
});
angular.module('myApp', ['validationMod']);
希望它能奏效:)