【发布时间】:2016-09-04 14:27:05
【问题描述】:
所以我有两个不同的 html 页面、两个不同的 ng-apps 和两个控制器。我正在尝试在控制器和不同模块之间共享数据。
下面是应用程序的基本结构
index.html - indexController.js 登录.html - loginController.js
sharedService.js
angular.module('sharedService', []).service('SharedService', function() {
var SharedService;
SharedService = (function() {
function SharedService() {
console.log('initializing');
}
var _data;
SharedService.prototype.setData = function( data) {
_data = data;
/* method code... */
};
SharedService.prototype.getData = function( ) {
return _data ;
};
return SharedService;
})();
if (typeof(window.angularSharedService) === 'undefined' || window.angularSharedService === null) {
window.angularSharedService = new SharedService();
}
return window.angularSharedService;});
angular.module("loginApp", ['sharedService'])
controller("loginCtrl",[
'SharedService', function(SharedService){
SharedService.setData(data);
}
angular.module("mainApp", ['sharedService'])
controller("someCtrl",[
'SharedService', function(SharedService){
console.log(SharedService.getData());
}
问题是因为应用程序不同,我引用的是
<script src="sharedService.js"></script>
服务被初始化两次。当我从 loginApp 设置数据时设置数据,但是当我从 mainApp 查询数据时,它检索未定义,我怀疑这是因为服务再次初始化并且是 sharedService 的不同实例
【问题讨论】:
-
为什么要将服务实例放到
window对象上?为什么要将服务中的功能包装到 IIFE 中?在这种情况下,我会使用工厂,只需将共享值存储在工厂的对象中,并让一些工厂方法返回或写入值。
标签: javascript angularjs angularjs-scope angularjs-service angularjs-factory