【问题标题】:How to emit an AngularJS event from a popup?如何从弹出窗口中发出 AngularJS 事件?
【发布时间】:2016-06-01 02:03:48
【问题描述】:

场景:我有一个使用 Google 身份验证的 AngularJS 应用。

取决于资源,当 Angular 调用(我的)后端时,它可以返回一个请求 Oauth 令牌的响应。 在这种情况下,Angular 将显示一个带有该重定向 URL 的弹出窗口(不是 Bootstrap 的模式对话框)。

Google 将进行身份验证、请求许可并将用户发回给我。 有一个回调 URL 将处理“代码”并获取真正的令牌。此 callbak URL 将在该弹出窗口中被调用。

当我获得令牌时,弹出窗口应该自行关闭,并通知 Angular 再次尝试最后一个请求(现在我在用户会话中拥有令牌)

问题:弹出窗口如何发出 Angular 事件?

其实不需要是$rootScope.$emit,只是通知Angular的一种方式。

我看到了this option,但它似乎对 Angular 不太好 :(

【问题讨论】:

    标签: javascript angularjs popup


    【解决方案1】:

    你可以使用 localStorage 事件,看看这个演示:http://html5demos.com/storage-events

    // this should be in the main page
    $window.addEventListener('storage', function(event) { 
      if(event.key === 'login-notification') {
        // got it!
        // you can get the value from 
        // the notification with "event.newValue"
      }
    }, false);
    
    // send the event with just a setItem from the popup
    $window.localStorage.setItem('login-notification', 'ayy');
    

    【讨论】:

      【解决方案2】:

      首先创建一个服务。

      app.service("servicee", function(){
        return {
          set : function(k,v){
                this[k] = v;    
           },
           get : function (k){
              return this[k]
           }
        }
      });
      

      现在在弹出窗口中,您可以在服务中设置令牌,现在您可以在整个应用程序中使用该值。您还可以 $watch 服务中的特定键并在设置值时采取一些措施。

      【讨论】:

      • 你确定吗? Angular 服务将在两个浏览器窗口之间继续singleton
      • 哦,所以它必须在问题中不清楚的窗口之间是单例的。使用ng-storage模块,使用'set'方法将其设置为存储和'get ' 方法来检索它
      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2017-10-16
      • 2014-01-24
      相关资源
      最近更新 更多