你好我有2个不同的控制器,我想分享从第一个到第二个的一些数据。
第一控制器:
validationApp.controller('loginCtrl'['auth','resetpass','$scope',function(auth,resetpass,$scope) {
$scope.login = function() {
auth.login($scope);
};
身份验证服务是:
validationApp.service('auth',function ($http,ipCookie,$rootScope,$state,localStorageService) {
$rootScope.authorized = false;
// function to submit the form after all validation has occurred
this.login = function ($scope) {
var hash1 =CryptoJS.SHA256($scope.password)
var rootElem = {};
var loginRequest = {
username: $scope.username,
hash: hash1.toString(CryptoJS.enc.Hex)
};
rootElem.loginRequest = loginRequest;
var makejson = JSON.stringify(rootElem);
$http({
method: 'PUT',
url: url+'/users/'+ $scope.username +'/login/',
data: makejson,
headers:{'Content-Type':'application/json'}
})
.success(function (data,status){
if (200 == status) {
if((data.loginResponse.roles[0] == "USER") && (data.loginResponse.roles[1] == "ADMIN")){
$rootScope.authorized = true;
$state.go('admin');
}
else {
$rootScope.authorized = true;
$state.go('user');
}
}
})
.error(function(data,status){
if (400 == status) {
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(401 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(500 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
})
}
data是Backend返回的JSON。
我想在第二个控制器中共享一些JSON数据,例如data.loginResponse.username。
第二个控制器是:
validationApp.controller('Secondcontroller'['auth','$scope','$state',function(auth,$scope){}]);
登录后欢迎使用{{username}}。
答案 0 :(得分:0)
如果你想将数据共享到另一个控制器,你可以使用$ rootScope,如果你只需要第一个控制器的用户名,如下所示:
你的第一个控制者:
validationApp.controller('Firstcontroller', function(.....){
$scope.login = function() {
var data = auth.login($scope);
$rootScope.username = data.loginResponse.username;
};
});
你的第二个控制者:
validationApp.controller('Secondcontroller', function(.....){
You could access $rootScope.username inside here...
});