我有MainController
和ChatController
。用户使用username
,passwod
和jobname
登录,由MainController
控制,但在ChatController
中,我仍需要参数jobname
,想知道如何将其传递给ChatController
?
我在服务Auth
中编写了'saveJobname'和'getJobname'方法,但getJobname
效果很好但saveJobname
没有通过console.log(..)
语句看到在ChatController
。
以下是一些相关代码:
// ---------------------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;
});
我更喜欢不使用$rootScope
的解决方案,请建议。
非常感谢。
答案 0 :(得分:1)
在Auth
工厂内添加一个类似authFactory.info = {}
的变量,您可以定义username
,password
& myjobname
。
在使用它们时,你需要在控制器中绑定信息对象,如
$scope.info = Auth.info
Auth
工厂就像这样
// 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;
});