Angularjs从纯JS函数调用$scope.function

Angularjs call $scope.function from plain JS function

本文关键字:scope function 函数调用 从纯 JS Angularjs      更新时间:2023-09-26

我正在尝试实现一个谷歌重述,我能够在的帮助下验证用户是人类

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

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

主Html,我已经包括-

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