javascript - $window 对象在其他模块中不可用

标签 javascript angularjs

我为 AngularJS 应用创建了两个独立的模块。在我登录后的第一个模块中,我将登录信息和 API key 存储在 $window 对象中。

$window.sessionStorage["apiKey"] = apiKey;
$window.sessionStorage["profile"] = profile;

但是,我无法访问第二个模块中的窗口对象。

我的问题:
我可以使用任何工厂服务从其他模块访问窗口对象吗?
或者,如何保留 $window 对象中的属性?

最佳答案

您应该为此目的使用服务

创作

var myService = function ($http) { // injecting $http just for the sake of it
    var service = {};
    service.name = "My Service";

    return service;
};

添加到模块

app.service('myService', ['$http', myService]);

注入(inject) Controller

app.controller('MyController', ['$scope', 'myService', function ($scope, myService) {
    $scope.serviceName = myService.name;
}]);

关于javascript - $window 对象在其他模块中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27395249/

相关文章:

javascript - 无法在我的网络应用程序中访问 firebase 实时数据库

javascript - 用于至少一个字母表 (A-z) 的名称验证的正则表达式

node.js - MEAN 项目 - 组织

javascript - 无法从 child 那里获取 CSS 属性?

javascript - angularjs,browserify + 下划线

javascript - 在悬停时突出显示 Bootstrap 行

javascript - 在文档就绪时根据 URL 参数选择选项并检查复选框的功能

javascript - 如何在 Google Colab 中使用 Svelte

AngularJS 和 Typescript : How to assign a class/type as a directive's controller?

html - 根据屏幕大小限制表格行数