脚本
>我有一个服务UserService,维护用户的(布尔)sessionStatus.
>视图有条件地在ng-show = sessionStatus上显示[logoUT](即如果未登录(false),则不显示).
>因此,ViewController的sessionStatus应始终与UserService的SessionStatus相匹配……对吗?
>如果在可见时单击[logoUT],它会执行一些logy outty事件,sessionStatus值更改,并且视图应更新为ng-show的新结果….
问题
>目前,单击logout似乎没有更新var UserService.sessionStatus?
>当UserService.logout()发生并更改UserService.sessionStatus时,如何更新$scope.sessionStatus?
>如何将更改的$scope映射到ng-show?
档
视图
<a ng-show="sessionStatus" ng-click="logout()">logout</a>
视图控制器
app.controller('AppController',function($scope,$interval,$http,UserService) { $scope.logout = function() { UserService.logout(); } // This ain't working $scope.$watch(UserService.sessionStatus,function() { $scope.sessionStatus = UserService.sessionStatus; }); });
UserService
注意:appUser是HTML头中注入的全局变量(一个hacky修复,直到我得到会话/ cookie的东西正常工作)
app.factory('UserService',function($http) { var pre; var sessionStatus; function init() { // Logged in : Logged out pre = appUser.user != undefined ? appUser.user : { name: 'Logged out',uid: '0' }; sessionStatus = pre.uid != "0" ? true : false; } function resetSession() { appUser = null; init(); } init(); return { sessionStatus: function() { return sessionStatus; },// update on change! logout: function() { $http.get("/logout").then(function (data,status,headers,config) { resetSession(); }) } }; });