从javascript函数调用指令中定义的控制器中的方法

时间:2014-09-24 13:58:09

标签: javascript angularjs

我正在寻找一种方法来调用来自全局函数的指令中定义的控制器中的方法。我能够成功地在模块中定义控制器,并在普通的html元素中使用ng-controller声明控制器。然后我从javascript函数得到控制器和范围,如下所示:

function signinCallback(authResult) {
    var googleLoginControllerElement = document.getElementById('googlelogin');
    var ctrlScope = angular.element(googleLoginControllerElement).scope();
    var controller = angular.element(googleLoginControllerElement).controller();

    ctrlScope.$apply(function() {
        controller.signinCallBack(authResult);
    });
}

但是当我将控制器的定义移动到指令的定义时,我无法找到一种方法来执行此操作(将控制器定义移动到指令后的新代码):

var googleLogin = angular.module('GoogleLogin', []);

googleLogin.directive('googleLogin', function() {
    return {

    restrict: 'E',
    controller: function() {
    // Initialize google login api
    (function() {
        var po = document.createElement('script'); 
        po.type = 'text/javascript';
        po.async = true;
        po.src = 'https://apis.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(po, s);
     })();

         /*
         * 1: not logged in.
         * 2: logged in.
         * 3: login failed.
         * 4: logout failed.
         */
         this.state = 1;

         this.signinCallBack = function(authResult) {
         if (authResult['status']['signed_in']) {
             console.log('authResult: ' + JSON.stringify(authResult));
             this.state = 2;
         } else if (authResult.error === "user_signed_out") {
             console.log('Sign-in state: ' + authResult['error']);
                 this.state = 1;
         }
        };

        this.logout = function() {
            try {
                gapi.auth.signOut();
                this.state = 1;
             } catch(e) {
                 this.state = 4;
             }
        };

        this.isLoggedIn = function() {
            return this.state == 2;
        };
    },
    controllerAs: 'googleLoginCtrl',
    templateUrl: '../templates/google_login.html'
};
});

在我的html中,我使用这样的指令:

<google-login></google-login>

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情(我不确定它是否会起作用,让我知道):

window.globalSigninCallBack = this.signinCallBack;

在你的指令里面:

googleLogin.directive('googleLogin', function() {
    return {

    restrict: 'E',
    controller: function() {
    // Initialize google login api
    (function() {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/client:plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
        })();

         /*
         * 1: not logged in.
         * 2: logged in.
         * 3: login failed.
         * 4: logout failed.
         */
         this.state = 1;

         this.signinCallBack = function(authResult) {
         if (authResult['status']['signed_in']) {
             console.log('authResult: ' + JSON.stringify(authResult));
             this.state = 2;
         } else if (authResult.error === "user_signed_out") {
             console.log('Sign-in state: ' + authResult['error']);
                 this.state = 1;
         }
        };

        window.globalSigninCallBack = this.signinCallBack;

        this.logout = function() {
            try {
                gapi.auth.signOut();
                this.state = 1;
             } catch(e) {
                 this.state = 4;
             }
        };

        this.isLoggedIn = function() {
            return this.state == 2;
        };
    },
    controllerAs: 'googleLoginCtrl',
    templateUrl: '../templates/google_login.html'
};
});

然后在代码调用中:

window.globalSigninCallBack(authResult);

但这是非常hacky的解决方法,我永远不会在我的代码中使用它:)

答案 1 :(得分:0)

您需要指定指令必须使用的范围。

请参阅此文档:https://docs.angularjs.org/guide/directive

**编辑:**

我为你的元素提供了一个id,以便我可以访问它。

<google-login id="mybtn"></google-login>

&安培;将您的全局功能更改为。

function signinCallback(authResult) {
//  alert('I came here also inside callback global');

  var googleLoginControllerElement = document.getElementById('mybtn');
  var ctrlScope = angular.element(googleLoginControllerElement).scope();

 ctrlScope.$apply(function() {
      ctrlScope.googleLoginCtrl.signinCallBack(authResult);
     });

  //      ctrlScope.googleLoginCtrl.signinCallBack(authResult);
  //alert('I came here also inside callback global end');

}

我正在尝试ctrlScope.controller,但是监督了它的名字。