我是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 :(得分:2)
您的问题在于以下几行:
$stateProvider
.state('training', {
url: "/training",
templateUrl: "partials/training.html",
controller: function($scope, $http, $state, $uibModal){
console.log("Main Training State");
$http.get('/api/training').success(function (response){
var data = response;
$scope.courses=data.courses;
}).error(function(err,status){
console.log(err);
});
$scope.openReadMoreModal = function (course) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'readmoremodal.html',
controller: 'ModalInstanceCtrl',
resolve: {
modalObject: course
}
});
};
}
})
.state('mytraining', {
url: "training/me",
templateUrl: "partials/training.html",
controller: function($scope, $http, $state, $uibModal){
console.log("get My Events in the training html");
$http.get('/api/training/myevents').success(function (response){
console.log("response :"+ response);
$scope.courses = response.courses;
}).error(function(err,status){
console.log(err);
});
$scope.openReadMoreModal = function (course) {
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'readmoremodal.html',
controller: 'ModalInstanceCtrl',
resolve: {
modalObject: course
}
});
};
}
})
删除angular.module("main", ["app", "controller"])
angular.module("main", [])
.factory("authService", authService);
或将其更改为angular.module("main", [])
。注意没有第二个参数。