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:
or
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?
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>
I will tell you how I do it.
In particularly your case, service would be good. You can place your logout logic in service recipe. Call that service where it is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With