Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create isLoggedIn function in AngularJS that can be accessed in any controller or template?

I need an isLoggedIn() function that both controllers and templates all have access to (templates need it in order to do something like ng-show="isLoggedIn()"). What's the best way to do this?

If the answer is a service, then is it possible to access a service from within a template, or does each of my controllers need to create a wrapper function for the template to see it (in $scope)?

like image 284
Mike Crittenden Avatar asked Jun 29 '12 13:06

Mike Crittenden


1 Answers

I usually have a 'MainCtrl' in my body tag and put global stuff in it.

<body ng-controller="MainCtrl">
  ...
</body>

function MainCtrl($scope, authService) {
  $scope.isLoggedIn = function() {
    return authService.isLoggedIn();
  }
}

Then every other scope will inherit the isLoggedIn function.

You can also put the isLoggedIn on the $rootScope, but I like this way.

like image 50
Andrew Joslin Avatar answered Nov 01 '22 23:11

Andrew Joslin