Angularjs从普通JS函数调用$ scope.function

时间:2016-04-29 04:39:25

标签: javascript angularjs recaptcha

我正在尝试实施Google Recapcha, 我可以在它的帮助下验证用户是否为人,

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

到目前为止,这是我的代码 -

主要HTML,我已经包含 -

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

Html partial -

    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");
    }
}]);

1 个答案:

答案 0 :(得分: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();
    };