我对angularJS比较陌生,我想知道下面这个问题最干净的解决方案是什么。假设我有一个如下的表单
<form name="contactform">
<select id="salutation" name="salutation" required="true" ng-model="contactRequest.salutation"><option value="Herr" selected="">Herr</option><option value="Frau">Frau</option></select>
<img width="255" height="70" alt="" src="/website/var/tmp/aed4d639a26c4614cdac2a967381c61c.png" name="captcha[img]">
<captcha-reloader reload-url="/refresh-captcha" img-tag-name="captcha[img]" hidden-field-name="captcha[id]"></captcha-reloader>
<input type="text" name="captcha[input]" required="true" ng-model="contactRequest.captcha.input">
<input type="text" style="display: none;" ng-model="contactRequest.captcha.id" value="aed4d639a26c4614cdac2a967381c61c" name="captcha[id]">
...
可以看到,它使用一个指令来显示一个按钮,该按钮将重新加载CAPTCHA。它被定义为
myApp.directive('captchaReloader', function () {
return {
restrict: 'E',
scope: {
reloadUrl: '@',
imgTagName: '@',
hiddenFieldName: '@'
}, //isolate scope
template: '<a href="" ng-click="reloadCaptcha()" class="captcha-reload"></a>',
link: function (scope, element, attrs) {
},
controller: function ($scope, $element, $attrs, $http) {
$scope.reloadCaptcha = function () {
$http.get($attrs.reloadUrl).then(function (res) {
angular.element('img[name="' + $attrs.imgTagName + '"]').attr('src', res.data.imgSrc);
angular.element('input[name="' + $attrs.hiddenFieldName + '"]').val(res.data.id);
angular.element('input[name="' + $attrs.hiddenFieldName + '"]').trigger('input');
});
};
}
};
)};
如果我点击按钮,验证码图像和值(隐藏字段)被更新。到目前为止运行良好。
现在,我想在控制器中处理表单提交(参见下面的方法)。如果出现错误(服务器端验证),则必须更新captcha。我不知道触发指令中定义的更新过程的最佳方式是什么。有人能帮忙吗? myApp.controller('KontaktCtrl', function ($scope, $location, CustomerDataService, CaptchaService) {
$scope.contactRequest = {
salutation: 'Herr',
captcha: {
id: initialCaptchaId
}
};
$scope.errors = {};
$scope.submitAction = function () {
CustomerDataService.sendRequest($scope.contactRequest).then(function (res) {
var data = res.data;
if (res.data.data !== null) { //errors in form. Display them
//error handling
$scope.reloadCaptcha();
} else {
goToHomeView();
}
}, function (error) {
console.log('An error occurred while updating!', error);
});
};
var goToHomeView = function () {
$location.path('/');
};
});
另外,我必须初始化选择框和验证码的值,否则它们不会被发送(因为它们是不变的)。有什么办法可以避免这种情况吗?
PS:我发现了一个reCAPTCHA指令,但由于样式限制,reCAPTCHA是没有选项。
步骤很简单…
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer></script>
<script>
var onloadCallback = function() {
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'Site-Key-',
'theme' : 'light'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
现在在表单上输入
<div id="example1"></div>
<p style="color:red;">{{ captcha_status }}</p>
Validate with angular
if(grecaptcha.getResponse(widgetId1)==''){
$scope.captcha_status='Please verify captha.';
return;
}