我试图在角度站点上实现Recaptcha V2.
我正在使用angular translate,我不知道如何使用$scope提供的正确语言重新生成reCaptcha对象
有什么办法吗?或使用正确的lang重新加载对象的过程?
谢谢
根据API的限制,您可以动态加载脚本:
原文链接:https://www.f2er.com/angularjs/141790.html加载脚本的功能
(source)
function loadScript(url,callback) { // Adding the script tag to the head as suggested before var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // Fire the loading head.appendChild(script); //modification so we can remove this after return script; }
注意:这是一个常规的JS函数
动态加载脚本
在你的Angular控制器中
$scope.loadGoogleRecaptcha = function (id,lang) { /// using timeout not to use $apply $timeout(function () { //set default value var elemntID = id || false; var language = lang || 'en'; if (!elemntID) { console.warn('NO Id selected for re-captcha loading!') return false; } var element = document.getElementById(elemntID) if (angular.element(element).length == 0) { console.warn('provided id doesn\'t exist ',elemntID); return false; } //Delete oldscript if ($rootScope.addedScript) angular.element($rootScope.addedScript).remove(); //clear current recaptcha container angular.element(element).empty(); var url = "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=" + lang; return $window.loadScript(url,function () { console.log('Scipt loaded:',url); }) }); }
使用angular-translate-localStorage使用当前语言初始化验证码
$rootScope.addedScript = $scope.loadGoogleRecaptcha('g-recaptcha-register',$window.localStorage.getItem( 'NG_TRANSLATE_LANG_KEY'));
切换语言的功能样本
$rootScope.changeLanguage = function (langKey) { $translate.use(langKey); $rootScope.selectedLanguage = langKey; $scope.loadGoogleRecaptcha('g-recaptcha-register',langKey); };
或者你可以使用观察者
$scope.$watch( 'selectedLanguage',function (n,o) { //putting if to prevent double fetch the first time if (!!n && n != o){ $rootScope.addedScript = $scope.loadGoogleRecaptcha('g-recaptcha-register',n); } } );