[英]Share data, events across multiple angular modules
我正在开发一些使用多个模块的项目
我有一个内核模块和其他依赖于内核的模块
angular.module('kernel', []);
...
angular.('process-manager', [ 'kernel', 'ui.router' ])
...
etc
我需要在所有模块之间共享一些数据,并在所有模块之间广播一些事件。
现在在子模块中,我使用的是内核模块的$ rootScope,该内核模块在$ window对象中定义为全局对象
.factory('$appScope', appScope)
...
appScope.$inject = ['$window', '$rootScope'];
function appScope($window, $rootScope: ng.IRootScopeService) {
if (angular.isDefined($window.superScope) === false) {
$window.superScope = $rootScope;
}
return $window.superScope;
}
有没有更好的解决方案来做这样的事情?
通过ng-app引导的EDIT内核模块以及通过angular.bootstrap()引导的其他模块
我看到您在代码中使用.factory()...
,即使我不确定您如何使用它,也可能使用正确的路径。
使用服务。 服务是单例,旨在保存可通过注入在您的应用程序甚至模块之间共享的数据。 至于广播事件,可以在$rootScope
上调用$broadcast
,也可以$watch
所有模块中服务数据的更改。
有更好的回答类似的问题在这里 。
这是一个例子:
angular.module('firstModule', []).service('MyService', function () {
return {
some: 'data'
};
}).controller('someController', function ($scope, MyService) {
$scope.$watch(function () {
return MyService.some;
}, function (some) {
// This runs whenever the service's data changes
console.log(some.data, 'logged in first module');
}, true);
});
angular.module('secondModule', ['firstModule']) // <-- this makes the first module's service available for injection in the second module
.controller('someController', function ($scope, MyService) {
$scope.$watch(function () {
return MyService.some;
}, function (some) {
// This runs whenever the service's data changes
console.log(some.data, 'logged in second module');
}, true);
})
可能会为每个模块重新实例化该服务,这可能会妨碍您跨模块进行通信的能力。 请事实检查我。 同时,Dennis Nerush的答案中建议的本地存储可能是更好的方法。 我发现https://github.com/gsklee/ngStorage是Angular的很好补充。
我建议使用本地存储在模块之间传递数据并保持数据一致。 这是一个很好的例子
http://www.codediesel.com/javascript/sharing-messages-and-data-across-windows-using-localstorage/
在所需的模块中注册一个事件列表器为'$ scope。$ on('changedVariable',function(event,args){//在列表模块中做你的事});“
在需要夸张的模块中:$ scope。$ broadcast('changedVariable',{change:someValue}); 准确地说,您已经完成了! ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.