我正在为像这样的登录系统实现角度资源
.. factory.js
//Create a factory for the Login API
angular.module(...)
.factory('LoginEntity', ['$resource', function ($resource) {
return $resource(
'API/sigin',
{
save: {method: 'POST'},
update: {method: 'PUT'}
}
);
}])
... controller.js
.controller('xxxController', ['LoginEntity', function(LoginEntity, $rootScope){
//in Controller add LoginEntity dependency
$rootScope.loggedinuser = {};
LoginEntity.save({
username: user.userName,
password: user.password
},
function (response) {
//success callback
$rootScope.loggedinuser = response;
},
function () {
//error callback
});
}]);
... AppCtrl
.controller('AppCtrl',function($scope,$rootScope){
username = $rootScope.loggedinuser.username;
}
这就是我所拥有的,但是在根控制器中似乎无法在App控制器中访问。
任何帮助或帮助都将受到高度赞赏
答案 0 :(得分:2)
你的controller.js有错误,请将$rootScope
添加到您的代码中,如下所示:
.controller('xxxController', ['LoginEntity', '$rootScope', function(LoginEntity, $rootScope){
//in Controller add LoginEntity dependency
$rootScope.loggedinuser = {};
LoginEntity.save({
username: user.userName,
password: user.password
},
function (response) {
//success callback
$rootScope.loggedinuser = response;
},
function () {
//error callback
});
}]);
答案 1 :(得分:1)
将您的代码更改为:
.controller('xxxController', ['LoginEntity', '$rootScope', function(LoginEntity, $rootScope){
///
}]);
... AppCtrl
.controller('AppCtrl', ['$scope, '$rootScope', function($scope,$rootScope){
///
}]
答案 2 :(得分:0)
使用依赖注入。这应该有希望工作:
.controller('AppCtrl',['$scope', '$rootScope', function($scope,$rootScope){
username = $rootScope.loggedinuser.username;
}])
这也确保在缩小时,行为不会中断,变量名称会自动更改。
答案 3 :(得分:0)
您必须将$ rootScope注入您的控制器
.controller('xxxController', ['LoginEntity', '$rootScope', function(LoginEntity, $rootScope){
// TO DO Something
}]);
或隐式注释(小心缩小代码)
.controller('xxxController', function(LoginEntity, $rootScope){
// TO DO Something
});
答案 4 :(得分:0)
在控制器中注入$ rootScope
.controller('AppCtrl',['$scope', '$rootScope', function($scope,$rootScope){
$rootScope.loggedinuser = "your user detail"
}])
答案 5 :(得分:0)
我不确定这是不是你想要的。如果要将loggedinuser保留在localStorage中,则应该成功回调。
...AppCtrl
.controller('AppCtrl', ['LoginEntity', '$scope', '$rootScope', function(LoginEntity, $scope,$rootScope){
LoginEntity.save({
username: user.userName,
password: user.password
},
function (response) {
//success callback
localStorage.setItem('loggedinuser', JSON.stringify(response));
},
function () {
//error callback
LoggerService.error('Landing page:error during LoadTestEntity initiation');
});
}