【发布时间】:2014-03-26 00:53:02
【问题描述】:
我正在编写一些小练习来自学 AngularJS,并且我正在尝试编写一些简单的用户授权任务。我有一个表单来收集/输入用户名和密码,然后使用$http 和 CORS(因为我的 REST 服务在不同的端口上运行)将它们发送到休息服务,检查它们是否匹配我返回一个 UUID 并创建一个令牌,然后我将 $broadcast 的已登录值设置为 true,即在 $rootScope 上,类似这样。
// this is in a service I call 'authService'
this.login = function (user) {
return $http({method: 'POST', url: 'http://127.0.0.1:3000/login', data: user})
.then(function (response) {
// set up a local storage token
storageService.setLocalStorage('token', response.data[0].uuid);
// broadCast is loggedIn - we have a match
$rootScope.loggedInUser = true; // this is set to false at the .run() of the app
$rootScope.$broadcast('LoggedIn');
return 1;
}, function () {
// return http code later
return 0;
});
};
this.getLoggedIn = function () {
return $rootScope.loggedInUser;
};
现在在一个单独的菜单视图中,我有以下条件(authService 作为对菜单控制器的依赖添加):
<div id="logIn" ng-show="!authService.getLoggedIn()">...</div>
现在,当我第一次加载应用程序时,条件是正确的,但是如果用户正确登录(因此 div)未显示,我希望更新此条件。在菜单控制器中我有以下代码,它似乎没有做任何事情?
$scope.$on('LoggedIn', function () {
authService.getLoggedIn(); // doesn't update the view?
console.log($rootScope.loggedInUser); // returns true
console.log(authService.getLoggedIn()); // returns true
});
$scope.$watch('loggedInUser', function () {
console.log('loggedInUser has changed ' + $rootScope.loggedInUser);
// This runs once when we set $rootScope.loggedInUser in the .run() of the app, output is: 'loggedInUser has changed false'
// then when we have successfully logged in again, output is 'loggedInUser has changed true'
});
好的,所以当我更改 $rootScope.loggedInUser 时,我的菜单视图中 <div> 的条件没有更新,我的方法有问题,有人可以给我一些建议或纠正我的方法对此。谢谢
【问题讨论】:
-
ng-show绑定到像$scope.isLogon这样的作用域值或返回真或假的作用域函数。authService.getLoggedIn()未定义或至少未在您在此处显示的代码中定义。所以意味着authService.getLoggedIn()总是错误的。 -
抱歉,authService.getLoggedIn() 是在我作为依赖项添加到菜单控制器中的服务中定义的,因此当我登录 console.log(authService.getLoggedIn());和 $scope.$watch('loggedInUser' function(){}) 在控制器中触发但视图没有更新?
-
视图不能访问 authService,你能在你的菜单控制器中做代理
authService.getLoggedIn()吗?喜欢$scope. getAuth = function() { return authService.getLoggedIn() }。我也真的不认为需要在您的用例中涉及 rootScope。
标签: javascript angularjs