Currently, I am facing a challenge with my MainController
and ChatController
. Users log in using parameters like username
, password
, and jobname
which are controlled by the MainController
. However, in the ChatController
, I still require the parameter jobname
and I am unsure of how to pass it to the ChatController
.
I attempted to write methods 'saveJobname' and 'getJobname' in the Auth
service. Surprisingly, while getJobname
functions properly, saveJobname
does not work as expected, as indicated by the console.log(..)
statement in the ChatController
.
Below are some snippets of relevant code:
// ---------------------MainController--------------------
app.controller('MainController', ['Auth', '$scope', '$window', '$rootScope', function(Auth, $scope, $rootScope, $window) {
$scope.info = Auth.info;
var vm = this;
vm.loginData = {};
vm.doLogin = function() {
// ...login processing
Auth
.login(vm.loginData.username, vm.loginData.password)
.success(function(data) {
// ...some more code here
if (data.success) { // if login successfully, then save jobname
$scope.info.myjobname = vm.loginData.jobname;
//Auth.saveJobname(vm.loginData.jobname); //does NOT work either
// ...some more codes here
$window.location.href = $window.location.href + '/../job.html';
}
});
};
}]);
// --------------------ChatController----------------------
app.controller('ChatController', ['Auth', ChatController]);
function ChatController(Auth) {
// ...come other codes here;
console.log(Auth.info.myjobname); // it prints 'hello.world!' but not 'vm.loginData.jobname';
// ...come other codes here;
}
// ------------------- AuthService ------------------------
app.factory('Auth', function($http, $q) {
var authFactory = {};
authFactory.info = {
myjobname: 'hello.world!'
};
// get the API from auth.post('/login', function(...){...})
authFactory.login = function(username, password) {
return $http.post('http://localhost:8080/auth/login', {
username: username,
password: password
}).success(function(data) {
//some code here about token processing
return data;
});
};
authFactory.saveJobname = function(jobname) {
authFactory.info.myjobname = jobname;
};
authFactory.getJobname = function() {
return authFactory.info.myjobname;
};
return authFactory;
});
I would appreciate solutions that do not involve $rootScope
. Please provide your insights and guidance.
Thank you very much.