2016-04-29 45 views
5

调用$ scope.function我想实现一个谷歌recapcha, 我能够验证用户是人类与它的帮助下,Angularjs从纯JS功能

的reCapcha代码调用名为回调函数“ verifyCallback'在我的代码中, 此外,我想调用写在我的控制器范围内的AngularJS函数。

这里是我的代码至今 -

主HTML,我included-

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script> 

的Html部分 -

var onloadCallback = function() 
    { 
     grecaptcha.render('loginCapcha', { 
      'sitekey' : 'someKey', 
      'callback' : verifyCallback, 
      'theme':'dark' 

     }); 
    }; 

    var verifyCallback = function(response) 
    { 
     //I get a response if user is able to solve the Capcha challenge 
     console.log(response); 

     //I want to call the function called 'auth' written in my AngularJS controller 
     var scope = angular.element(document.getElementById('#loginCapcha')).scope(); 
     scope.auth(); 
    }; 

    <div id="loginCapcha"></div> 

AngularJS控制器 -

var _myApp = angular.module('homeApp',[]); 

_myApp.controller('loginController',['$scope', 
function($scope){ 

    $scope.auth = function() 
    { 
     console.log("Auth called"); 
    } 
}]); 
+0

我认为最好的解决办法是直接使用的ReCaptcha JS API而不是在这里进行通用设置。如果您四处搜索,但不确定哪一个是最新的和/或无bug的,那么有几个recaptcha指令。 https://developers.google.com/recaptcha/docs/display#js_api这里有一个http://vividcortex.github.io/angular-recaptcha/ – shaunhusain

+1

@shaun感谢您的链接,我试图实现一个基本的工作代码,我会研究你给定的链接。 –

回答

5
<div ng-controller='loginController' id='yourControllerElementID'> 

</div> 

对于上述情况下,使用下面的代码:

var scope = angular.element(document.getElementById('yourControllerElementID')).scope(); 
scope.auth(); 

所以,你的方法是这样的:

var verifyCallback = function(response) 
    { 
     //I get a response if user is able to solve the Capcha challenge 
     console.log(response); 

     //I want to call the function called 'auth' written in my AngularJS controller 
     var scope = angular.element(document.getElementById('#yourControllerElementID')).scope(); 
     scope.auth(); 
    }; 
+0

'yourControllerElementID'是我的控制器名称或我的控制器内的函数名称? –

+0

@AniruddhaRaje更新回答,请检查。 –

+0

我编辑了代码,它给了我一个 - Uncaught ReferenceError:$ scope没有定义 –