Javascript 如何使用 ng-messages 在 Angularjs 中显示服务器错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28157377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display server errors in Angularjs with ng-messages
提问by Leon
I have have my angular app validating a sign-up form. On submit, the server also validates the data. I'm outputting error messages in angular using ng-messages.
我有我的 angular 应用程序验证注册表单。提交时,服务器还会验证数据。我正在使用 ng-messages 以角度输出错误消息。
Here is a shortened version of my form, which works perfectly so far.
这是我的表单的缩短版本,到目前为止效果很好。
<form name="signUpForm" novalidate data-ng-submit="attemptSignUp()">
<label for="firstName">First name</label>
<input type="email" name="email" id="email" required data-ng-model="data.user.email" />
<div class="error" data-ng-messages="signUpForm.email.$error" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="required">Please provide your email</p>
</div>
</form>
The server verifies the email address is unique, and if not, returns a 422 error (from Laravel 5), with an array of errors.
服务器验证电子邮件地址是否唯一,如果不是,则返回 422 错误(来自 Laravel 5),以及一系列错误。
[
'email' => 'This email is already in use'
]
I'd like to merge in this, and any other messages sent back from the server into their relevant ng-messagesblock. Any idea how I could accomplish it?
我想合并这个,以及从服务器发回的任何其他消息到它们的相关ng-messages块中。知道我怎么能做到吗?
回答by jornare
A simple solution is to have two arrays. One for client side and one for server side errors which is populated in your controller. You can hide the server side errors if client errors exists or opposit to avoid double messages.
一个简单的解决方案是有两个数组。一种用于客户端,另一种用于填充在控制器中的服务器端错误。如果客户端错误存在或相反,您可以隐藏服务器端错误以避免重复消息。
The reason I choose to have two arrays instead of populating the forms array is that the JavaScript controller should not know or be dependent on the structure of the HTML. The HTML AngularJS template should be bound to the controller, not opposit.
我选择有两个数组而不是填充 forms 数组的原因是 JavaScript 控制器不应该知道或依赖于 HTML 的结构。HTML AngularJS 模板应该绑定到控制器,而不是对立的。
<form name="signUpForm" novalidate data-ng-submit="attemptSignUp()">
<label for="email">E-mail
<input type="email" name="email" id="email" required data-ng-model="data.user.email" />
<div class="error" data-ng-messages="signUpForm.email.$error" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="required">Please provide your email</p>
</div>
<div class="error" data-ng-messages="serverErrors" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="emailexists">Email already exists</p>
</div>
</label
</form>
A note on the label: Users using screen-readers will not get your error messages read out loud to them if they are not wrapped inside the label.
标签上的注释:如果错误消息没有包裹在标签内,则使用屏幕阅读器的用户将不会向他们大声朗读错误消息。
回答by mengstrom
Well, this is not the most elegant solution since you really should leverage the asyncValidators in angular 1.3.x and then create your custom validation directives.
Resources
http://plnkr.co/edit/s4jJAOqehBkFUC9osMsy?p=previewfound in the post by this guy.
Possibly here http://odetocode.com/blogs/scott/archive/2014/10/16/working-with-validators-and-messages-in-angularjs.aspx
And of course in the docs
好吧,这不是最优雅的解决方案,因为您确实应该利用 angular 1.3.x 中的 asyncValidators,然后创建您的自定义验证指令。
资源
http://plnkr.co/edit/s4jJAOqehBkFUC9osMsy?p=preview在此人的帖子中找到。
当然在文档中
But be cautiousas this is not in any way a complete example ready to be used. It's mostly here for demo purpose and to sort of give you an idea where to start. I have not bothered with clearing any previous errors, revalidating the form or taken into account other validation errors.
但要小心,因为这绝不是一个可以使用的完整示例。它主要用于演示目的,并让您知道从哪里开始。我没有费心清除任何以前的错误,重新验证表单或考虑其他验证错误。
Awesomeness
令人敬畏
Imagineyour controller looks like this
想象一下你的控制器看起来像这样
$scope.serverValidations = {};
$scope.attemptSignUp = function(){
Api.validateEmail($scope.email).then(angular.noop, function(data){
$scope.serverValidations = data
for(prop in $scope.serverValidations){
if($scope.signUpForm[prop]){
angular.forEach($scope.serverValidations[prop],function(validation){
$scope.signUpForm[prop].$setValidity(validation.type, false);
});
}
}
});
}
and your response data containing validation errors look like this
包含验证错误的响应数据如下所示
{
email:[
{type:'unique', message:'This email is already in use'}
],
name:[
{type:'maxlength', message:'Your name is to long, get a new one :)'}
]
};
Then in your HTML you could do like this
然后在你的 HTML 中你可以这样做
<div class="error" data-ng-messages="signUpForm.name.$error" data-ng-cloak="">
<p data-ng-message="required">You don't have a name?</p>
<p ng-repeat="validation in serverValidations['name']" ng-message="{{validation.type}}">{{validation.message}}</p>
</div>
Here's a dirty Codepen for you: http://codepen.io/anon/pen/yyzMgG?editors=101When you press submit, after 2 seconds (the time it takes to hit the fake server) your server validations are presented.
这里有一个脏代码笔给你:http://codepen.io/anon/pen/yyzMgG?editors=101当你按下提交时,2 秒后(击中假服务器所需的时间)你的服务器验证就会出现。
回答by Artyom Trityak
First of all you should set validityand error messages
首先你应该设置validity和error messages
$scope.formErrors = {};
angular.forEach(errors, function(data, name) {
if (!vm.register_form[name]) {
return;
}
$scope.formErrors[name] = data.message;
//this will set errors->server to invalid state
$scope.register_form[name].$setValidity('server', false);
});
The next step will be rendering by ng-messages
下一步将通过渲染 ng-messages
<div ng-messages="register_form.email.$error">
<div ng-message="required">Email is required</div>
<div ng-message="email">Invalid email</div>
<div ng-message="server">{{formErrors.email}}</div>
</div>
回答by Greg P
I had a similar question, but the solutions did not work for me. What I did, and it is/was a hack/work around, was to send different errorcodes, and set a case statement.
我有一个类似的问题,但解决方案对我不起作用。我所做的,它是/是一个黑客/解决方法,是发送不同的错误代码,并设置一个 case 语句。

