我怎样才能从AngularJS异步验证返回错误上下文的信息? [英] How can I return error context information from an AngularJS async validator?
问题描述
我使用的是新AngularJS异步验证功能在1.3推出。我有一个指令,看起来像这样:
I'm using the new AngularJS async validators feature introduced in 1.3. I have a directive that looks like this:
angular.module('app')
.directive('usernameValidator', function(API_ENDPOINT, $http, $q, _) {
return {
require: 'ngModel',
link: function($scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(username) {
return $http.get(API_ENDPOINT.user, {userName: username})
.then(function(response) {
var username = response.data;
if (_.isEmpty(username)) {
return true;
} else {
return $q.reject(username.error);
}
}, function() {
return $q.reject();
});
};
}
};
});
我想以某种方式获得 username.error
的值到模型控制器范围这样我就可以把它显示给用户。显示静态的信息很容易,但我想显示一些服务器返回以及错误的上下文信息。
I'd like to somehow get the value of username.error
into the model controller scope so I can display it to the user. Displaying a static message is easy, however I want to display some of the error context information returned by the server as well.
有没有干净的方式做到这一点还是我坚持与模型控制器上设置属性?
Is there a clean way to do this or am I stuck with setting properties on the model controller?
编辑::要澄清,我不是在寻找一个一次性的解决方案,只是工作。我打算用此指令作为可重复使用的,干净封装的组件。这意味着直接写入到周围的范围或类似的东西可能是不接受的。
To clarify, I am not looking for a one-off solution that just works. I intend to use this directive as a reusable, cleanly encapsulated component. This means directly writing to the surrounding scope or anything like that is probably not acceptable.
推荐答案
确认指令,就像任何其他的指令,你有机会获得$范围,所以为什么不设置的值,因为它: $ scope.errors.username = username.error;
the validation directive is just like any other directive, you have access to $scope, so why not set the value as it: $scope.errors.username = username.error;
angular.module('app')
.directive('usernameValidator', function(API_ENDPOINT, $http, $q, _) {
return {
require: 'ngModel',
link: function($scope, element, attrs, ngModel) {
$scope.errors = $scope.errors | {}; //initialize it
ngModel.$asyncValidators.username = function(username) {
return $http.get(API_ENDPOINT.user, {userName: username})
.then(function(response) {
var username = response.data;
if (_.isEmpty(username)) {
return true;
} else {
$scope.errors.username = username.error; //set it here
return $q.reject(username.error);
}
}, function() {
return $q.reject();
});
};
}
};
});
我只是分开初始化它 $ scope.errors = $ scope.errors | {}; //初始化
因此,如果您希望它可以重复使用在多个指令 $ scope.errors
对象
I just initialized it separately $scope.errors = $scope.errors | {}; //initialize it
so that you can reuse $scope.errors
object in multiple directives if you wish it
这篇关于我怎样才能从AngularJS异步验证返回错误上下文的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!