我有一个在 ng-view 之外的 NavbarCtrl。我有一个登录控制器,它与服务对话以使用户登录。用户登录后,我希望导航栏使用用户的电子邮件地址进行更新。但是对于我的生活,我似乎无法让导航栏范围更新用户登录后加载到我的“Auth”服务中的数据。
这是我的主要 index.html:
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Brim</a>
<div class="pull-right" ng-controller="NavbarCtrl">
<div ng-click="refresh()">hello</div>
{{ user.email }}
</div>
</div>
</div>
</div>
<div class="container" ng-view>
我的服务:
.factory('Auth', function($resource) {
var authenticated = false;
var user = {};
return {
isAuthenticated: function () {
return authenticated;
},
getUser: function() {
return user;
},
login: function(loginUser, callback) {
user = {email:'email@email.com'}
authenticated = true;
callback(true);
//actual code for logging in taken out for brevity
}
}
})
还有我的登录和导航栏控制器:
function LoginCtrl($scope, $location, Auth) {
$scope.login = function() {
Auth.login($scope.user, function(success) {
if(success) $location.path('/dashboard');
//console.log(Auth.getUser())
});
}
}
function NavbarCtrl($scope, Auth) {
//thought this should work
$scope.user = Auth.getUser();
//experimenting unsuccessfully with $watch
$scope.$watch(Auth.isAuthenticated(),function () {
$scope.user = Auth.getUser()
})
//clicking on a refresh button is the only way I can get this to work
$scope.refresh = function() {
$scope.user = Auth.getUser()
}
}
根据我的研究,我会认为 $scope.user = Auth.getUser(); 会起作用,但事实并非如此,我完全不知道如何在用户登录时更新我的导航栏。提前感谢您的帮助。