【发布时间】:2014-06-27 00:50:19
【问题描述】:
我正在尝试构建一个登录模式,它将跨不同控制器更新模板(只是基本的用户信息 - 头像、姓名等)。大致遵循这个example,我的方法是直接在我的部分中绑定服务变量,如下所示:
部分:
<div ng-controller="TopBarControl">
<span>{{ userService.getInfo() }}</span>
</div>
服务:
.service('userService', function($http) {
this.userInfo = {
isLogged: false
}
this.getInfo = function() {
return this.userInfo;
}
this.loginInit = function(userName, password) {
$http.get('http://example.com/?json=get_nonce&controller=auth&method=generate_auth_cookie').success(
function(data, status, headers, config) {
var nonce = data.nonce;
$http.get('http://example.com/?json=auth/generate_auth_cookie&nonce='+nonce+'&username='+userName+'&password='+password).success(function(data, status, headers, config) {
if (data.status == 'ok') {
this.userInfo = [
{isLogged: true},
{username: data.user.username},
{firstName: data.user.firstname},
{lastName: data.user.lastname},
{avatar: data.user.avatar}
];
return userInfo;
}
/* handle errors and stuff*/
});
}
})
控制器:
.controller('TopBarControl', function($scope, $modal, userService) {
$scope.userService = userService;
$scope.openLogin = function() {
var modalInstance = $modal.open({
templateUrl: 'views/modal.html',
controller: ModalInstanceCtrl,
size: 'lg'
});
}
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userService) {
$scope.login = function () {
userService.loginInit(this.userName, this.password);
};
$scope.ok = function () {
$modalInstance.close($scope.returnResolveVariable);
};
};
所以,登录有效。数据被发送到服务器,正确的数据被成功带回应用程序。双向绑定排序有效 - 每次发生更改时,模板都会回调.getInfo() 并吐出userInfo 的值。问题是 userInfo 的值永远不会改变。我不知道我在loginInit 中设置变量的方式是否有些奇怪,或者我根本不了解服务如何处理这样的变量。
【问题讨论】:
-
在您的示例中,控制器的
userInfo和服务的userInfo变量之间的关系在哪里。它们不是同一个变量。 -
哎呀...被评论了 - 它只是我想要生成的数组的参考。为了清楚起见,我删除了它。
标签: javascript angularjs angularjs-scope angular-services