0

Let's say I have a variable flag called is_logged_in, I want it to be in scope in all my controllers. So that if I have {{is_logged_in}} on every page in my app, it will print it out.

How do I achieve this without writing duplicate code like this, in all my controllers:

function MyCtrl($scope, IsLoggedInService) {
$scope.is_logged_in = IsLoggedInService.IsLoggedIn();
}
beansontoast
  • 181
  • 2
  • 12

4 Answers4

0

Change to this:

$rootScope.is_logged_in = IsLoggedInService.IsLoggedIn();
Raghav Rangani
  • 843
  • 7
  • 23
0

Your best bet is to use the $rootScope. This, as the name implies, correspond to the root scope of your application and is therefore potentially available (via DI) in any of your controllers. All you need to do is add $rootScope as a DI dependency in each of your controllers that requires it:

function MyCtrl($scope, $rootScope {
  $rootScope...
}

In your templates, the $rootScope always available by referencing $root in an angular expression.

You would do something like this:

<p>{{$root.is_logged_in}}</p>
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
0

if you want to check whether the user is logged in or not i think the right approach to your problem is to use resolve property in the route, so the user can't navigate to certain pages if he isn't logged in and once he logged in you can inject the user object to the controller

for example to navigate to home page you must be logged in

.when("/home", {
templateUrl: "homeView.html",
controller: "homeController",
resolve: {
    user: function(AuthenticationService){
        return AuthenticationService.getUser();
    }
  }
})

app.controller("homeController", function ($scope, user) {
  $scope.user = user;
});

https://www.sitepoint.com/implementing-authentication-angular-applications/

and if you just want a global variable you can use $rootScope

avim101
  • 300
  • 1
  • 2
  • 9
-1

Another approach, yet using the $rootScope, is to use $broadcast to create an observer for that variable.

In order to do this, you should broadcast an event when this variable is changed, like this:

$rootScope.$broadcast('user_logged_in');

And then, watch it using the $on method. Here:

$scope.$on('user_logged_in', function(event, args) {
    // here you do what you want, like:
    $scope.logged_in = true;
});

If you want to know more about it, angular also provides the $emmit method, that is used when you want that scopes above yours listen to that event. ( you can find more here : $rootScope.$broadcast vs. $scope.$emit

Yet, you should read more about in the docs, What are scopes? and here: $rootScope.Scope

Community
  • 1
  • 1
CarvBru
  • 39
  • 4
  • For this to work correctly both the controllers from where broadcast is done to where it is received should be active at the same time as it is nothing but an event listener – Rahul Arora Jun 09 '16 at 18:51