Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS: where is better to put signOut logic?

in every my controller i have such code, which i execute when i click on some link in view:

  $scope.logout = function() {
    authenticationService.logout();
    $scope.isAuthUser = false;
    delete $localStorage.selectedModel;
    $location.path('/login').search('key', null);
  };

i'm new to angularJS and want to know: how is it better to do:

  • to put logic in service

or

  • to put logic in directive?

with directive: i know how to use controllers: $scope.isAuth = false; - with service: i didn't know hot to use it, except to write it as now in every controller, that it would be something like:

  $scope.logout = function() {
    authenticationService.logout();
    myNewService.logout();
    $scope.isAuthUser = false;
  };

view:

    <a href="javascript:void(0)" data-ng-click="logout()">              
      <span>Sign Out</span>
    </a>

but seems that it is bad too... how is it right to do?

like image 387
byCoder Avatar asked Jan 19 '26 05:01

byCoder


2 Answers

This logic has nothing to do with directives, this is for sure. You already have authenticationService so this is exactly the place to put business logic of the login/logout functionality. I would recommend to move this code from controller into this service.

When it's a part of the service, the only code in controller would be

$scope.logout = authenticationService.logout;

That's it. Controller should be as slim as possible and without business logic, view logic is fine, of course.

Now, regarding $scope.isAuthUser. isAuthUser sounds very much like a property of the authenticationService service, isn't it? After all authenticationService is an object which is supposed to hold methods and properties of the related model/datalayer. So again it should be moved into same service.

If you need to use this flag in templates (maybe show/hide some buttons, etc.) you could expose this service all together into $scope/$rootScope property. Say, in top level controller you could do something like this:

app.controller('mainController', ['$scope', 'authenticationService', function($scope, authenticationService) {
    $scope.auth = authenticationService;
}]);

and then in any template you could simply use

<a href="#/logout" ng-click="logout()" ng-show="auth.isAuthUser">Logout</a>
like image 131
dfsq Avatar answered Jan 20 '26 18:01

dfsq


I will tell you how I do it.

  • If you are executing some logic without any Ajax/API calls. Go for service.
  • If you are calling some API - Then Factory.
  • If you are working with templates/DOM-manipulation then Directive.

In particularly your case, service would be good. You can place your logout logic in service recipe. Call that service where it is required.

like image 35
Harsh Avatar answered Jan 20 '26 18:01

Harsh