2016-07-26 75 views
2

我對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** 
    }); 
} 
+0

通過plunker,html&js文件分享您的代碼? –

回答

2

你的問題是,這些行:

angular.module("main", ["app", "controller"]) 
angular.module("main", []) 
.factory("authService", authService); 

要麼消除angular.module("main", [])或將其更改爲angular.module("main")。注意沒有第二個參數。