我有一个mdDialog,可以在提交时进行一些服务器端验证。我正在尝试找到一种结合错误消息的方法。问题是我需要在每次提交尝试之前清除服务器端错误,并且我不想输入每个可能错误的名称。
所以我是通过为这些代码分配前缀并手动清除它来实现的。这看起来非常hacky。是否有更多Angular方法将服务器端错误添加到字段的$ error中,以便它们可以与ngMessages一起使用?
来自服务器的示例JSON错误响应(每个失败字段的一个属性):
{"name":"svr_nameduplicated", "anotherfield":"svr_somethingwrong", ...}
对话摘录:
<md-dialog-content>
<div class="md-dialog-content">
<md-input-container>
<label>Name:</label>
<input type="text" name="name" data-ng-model="product.name" md-maxlength="40" required/>
<div ng-messages="productForm.name.$error" role="alert">
<div ng-message="required">Name is required.</div>
<div ng-message="md-maxlength">Name is too long.</div>
<div ng-message="svr_nameduplicated">Duplicate name.</div>
</div>
</md-input-container>
</div>
</md-dialog-content>
控制器:
function EditProductDialogController($scope, $mdDialog, product, productIdx) {
$scope.productIdx = productIdx;
$scope.product = product;
$scope.cancel = function() {
$mdDialog.cancel();
}
$scope.save = function() {
clearServerSideErrors($scope.productForm);
if ($scope.productForm.$valid) {
var options = {headers : {'X-CSRF-TOKEN': self.csrf}};
$http.put(contextPath + '/prod/ang/update/' + product.id, product, options)
.then(function(response) {
$mdDialog.hide({product: $scope.product, productIdx: $scope.productIdx});
},
function(errResponse) {
addServerSideErrors($scope.productForm, errResponse.data);
});
}
}
}
Hackish实用程序函数:
// walk on form fields and set errors whose code starts with svr_ to valid
function clearServerSideErrors(form) {
for (var prop in form) {
if (form.hasOwnProperty(prop) && !prop.startsWith('$')) {
for (var prop2 in form[prop].$error) {
if (prop2.startsWith('svr_')) {
form[prop].$setValidity(prop2, true);
}
}
}
}
}
// walk on error object returned from server and add errors to $error of fields
function addServerSideErrors(form, errors) {
for (var prop in errors) {
form[prop].$setValidity(errors[prop], false);
}
}