AngularJS: angular scope property

Scenario

  • I have a UserService service that supports a (boolean) user sessionStatus .
  • As a result, [LOGOUT] is conditionally displayed on ng-show=sessionStatus (that is, if it is not logged in (false), no show).
  • sessionStatus of ViewController should always match UserService ... right?
  • If you click [LOGOUT] when it is visible, it will make some errors in the log, the value of sessionStatus will change, and the view should refresh with the new result of ng-show...

Problem

  • Currently pressing the exit button is not like updating var UserService.sessionStatus?
  • How to save the value of the variable $ scope.sessionStatus when UserService.logout () occurs and change UserService.sessionStatus?
    • How to match changing $ scope with ng-show?

Files

View

  <a ng-show="sessionStatus" ng-click="logout()">Logout</a> 

ViewController

  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; }); }); 

User service

NB: appUser is a nested global var in the head of HTML (hacker fix until I get session / cookie work)

  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(); }) } }; }); 
+6
source share
2 answers

Instead of watch just use the function scope, which returns the session status from service .

 $scope.sessionStatus = function() { return userService.sessionStatus(); }; 

Your exit link will look like this:

 <a ng-show="sessionStatus()" ng-click="logout()">Logout</a> 

Truncated Plunker for your functionality: http://plnkr.co/edit/u9mjQvdsvuSYTKMEfUwR?p=preview

+9
source

Using the scoped function is cleaner and the β€œright” way to execute it. However, for the sake of completeness, you could also fix your watch:

 $scope.$watch(function () { return UserService.sessionStatus; }, function() { $scope.sessionStatus = UserService.sessionStatus; }); 

The first argument to the $ watch method takes a WatchExpression, which can be a string or a method.

But then again, $ watch should not be used in controllers. Using the methods described above is cleaner and easier to test.

+2
source

Source: https://habr.com/ru/post/976676/


All Articles