这是一个 angularjs 指令,用于显示多个表单验证错误。
指令代码 -
app.directive('validationErrors', function($compile) {
return({
link : function($scope, el, attr) {
$scope.fld = attr.id;
$scope.individualValidationErrors = [];
var model = ((attr.ngModel).split('.'))[0];
$scope.validationErrors = {};
$scope.validationErrors[model] = {};
$scope.validationErrors[model][$scope.fld] = "";
var html = $compile(
'<div id="error-{{fld}}" style="color:red;">'+
'<ul>' +
'<li ng-repeat="error in individualValidationErrors[fld]">'+
'{{error}}' +
'</li>' +
'</ul>' +
'</div>'
)($scope);
$('input[id="'+$scope.fld+'"]').after(html);
$scope.$watch('validationErrors',
function(newV) {
$scope.fld = attr.id;
$scope.individualValidationErrors = [];
console.log(newV);
console.log($scope.validationErrors);
if ($scope.fld != undefined) {
$scope.individualValidationErrors[$scope.fld] = $scope.validationErrors[model][$scope.fld];
//console.log($scope.individualValidationErrors);
}
},
true
);
}
});
});
html代码 -
<form ng-submit="registration()">
<input validation-errors="validationErrors" maxlength="50" type="text" id="first_name" ng-model="User.first_name">
<input validation-errors="validationErrors" maxlength="50" type="text" id="last_name" ng-model="User.last_name">
<input validation-errors="validationErrors" maxlength="50" type="text" id="email" ng-model="User.email">
<input validation-errors="validationErrors" type="password" id="password" ng-model="User.password">
<input class="btn btn-info" type="submit" id="registration-sbmit" value="Submit">
</form>
表单的最后一个字段的错误会覆盖表单中的所有字段,因此它没有显示字段的单个错误.. $scope.validationErrors 变量设置在我想在指令中 $watch 的控制器中。