在不同模块之间共享出厂值
问题描述:
我对angularjs很新,我有三个模块和一个工厂。我想在不同模块之间分享工厂的价值。我不知道我在做什么错,因为在运行时,userRole在登录后一直没有更新。在不同模块之间共享出厂值
angular.module("main", ["app", "controller"])
angular.module("main", [])
.factory("authService", authService);
function authService(){
var userRole = "",
service = {
setRole : setRole,
getRole : getRole
};
return service
function setRole(role){
userRole = role;
}
function getRole(){
return userRole;
}
}
angular.module("controller", [])
.controller("Controller1", Controller)
Controller.$inject = ["authService"]
function Controller(authService){
afterCallLogin().then(data, function(){
authService.setRole(data.role);
console.log(authService.getRole()) // this print "user" **CORRECT**
});
}
angular.module('app', [])
.run('runApp', runApp);
runApp.$inject = ['$rootScope', '$state', '$stateParams', 'authService']
function runApp($rootScope, $state, $stateParams, authService){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
console.log(authService.getRole()) // this print an empty value, **DOES NOT CHANGE**
});
}
答
你的问题是,这些行:
angular.module("main", ["app", "controller"])
angular.module("main", [])
.factory("authService", authService);
要么消除angular.module("main", [])
或将其更改为angular.module("main")
。注意没有第二个参数。
通过plunker,html&js文件分享您的代码? –