【问题标题】:Why Angular.js variables not accessible in Cordova InAppBrowser's executeScript callback为什么在 Cordova InAppBrowser 的 executeScript 回调中无法访问 Angular.js 变量
【发布时间】:2014-05-26 12:54:54
【问题描述】:

我正在使用 cordova 开发基于 angular.js 的混合应用程序。执行以下操作后,我遇到了无法访问角度变量$(如$rootScope)的问题。

  1. cordova 和 angular.js 在此混合应用程序启动后立即完成初始化。
  2. 当用户点击特定按钮进行社交登录时,会调用以下loginTwitterAccount $scope 函数。

  3. loginTwitterAccount 使用“InAppBrowser”cordova 插件打开新窗口以加载外部授权页面,而不是本地页面。此授权是“授权码”授权类型。因此,如果用户在打开的窗口中授予对我的混合应用程序的访问权限,我的后端服务器会与 twitter 服务器交换访问令牌,然后将访问令牌从 twitter 服务器发送到我的混合应用程序的打开窗口。

    app.controller('LoginCtrl', function($scope, $rootScope) {
    ...
      $scope.loginTwitterAccount = function () {
        var ref = $window.open('/auth/login/twitter', '_blank', 'location=yes,toolbar=yes');    
        ref.addEventListener('loadstop', function(event) {
            if (event.url.match('/auth/login/twitter/callback/success')) {
                // content of this url includes access token data explained above.
                // so app can get the data as calling executeScript like the following
                if (event.url.match(successUrl)) {
                    ref.executeScript({
                        code: 'getResult();'
                    }, function (values) {
                        // I checked values[0].data has correct value that I want.
                        // At the other place, $rootscope.$on for 'social-login' is already registered.
                        $rootscope.$emit('social-login', values[0].data);
                        ref.close();
                    });
                 }
            }
        });
      };
    });
    

问题是$rootscope.$emit 不起作用,以及其他带有$ 的角度变量(如$scope)不起作用。我不知道为什么在使用 cordova 和 angular.js 时会发生这种情况。在这种情况下是否有任何遗漏点?提前致谢。

【问题讨论】:

    标签: cordova oauth-2.0 angularjs-scope inappbrowser cordova-plugins


    【解决方案1】:

    我发现上面的问题是因为 $rootScope.$emit 在 angular.js 世界之外被调用。为了解决这个问题,我应该用$rootScope.$apply 包裹$rootScope.$emit,如下所示。

            ...
            if (event.url.match(successUrl)) {
                ref.executeScript({
                    code: 'getResult();'
                }, function (values) {
                    // I checked values[0].data has correct value that I want.
                    // At the other place, $rootscope.$on for 'social-login' is already registered.
                    $rootScope.$apply(function () {
                        $rootScope.$emit('social-login', values[0].data);
                    }
                    ref.close();
                });
             }
             ...
    

    您可以在以下链接中找到 $apply 的更多详细信息。

    How do I use $scope.$watch and $scope.$apply in AngularJS?

    http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

    【讨论】:

    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多