Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Angular making a service accessable from everywhere

I have service that i am using to check if my users are allowed to see the content in my application.

i use it like this:

<tab ng-controller="LibraryRTLController" ng-if="authFactory.hasFeature('ReadyToLearn')">

However it doesnt seem to work properly because i would have to intialize it in every controller which seems redundant.

So my question is: is there someway that i can use a service globaly?

Please note that for reasons i can't begin to explain here i have to use ng-if so an attribute directive will not help me!

Update

So ive added it to my run function:

angular.module('app')
.run(function ($rootScope, AuthService, authFactory, $state) {
    $rootScope.authFactory = authFactory;
    $rootScope.$on('$stateChangeStart', function (event, next, toParams) {
        $state.newState = next;
        var authorizedRoles = next.data.authorizedRoles;
        if (!AuthService.isAuthorized(authorizedRoles)) {
            event.preventDefault();
            if (AuthService.isAuthenticated()) {
                // user is not allowed
            } else {
                // user is not logged in
                window.location.href = "http://" + window.location.hostname
            }
        }
    });
})

When debugging i am able to see that it is actually setting the variable correctly.

in my service ive created a function that simply just alerts:

function doesWork ()
{
    alert('true!');
}

Now back in my html i have:

<tab ng-controller="LibraryRTLController" ng-init="authFactory.doesWork()">

However without any results?

Upvotes: 3

Views: 70

Answers (2)

Wasiq Muhammad
Wasiq Muhammad

Reputation: 3118

Yes you can access service globally by referring the service name in main root file where you inject dependency

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
  $rootScope.authFactory = authFactory;
}]);

Upvotes: 0

dfsq
dfsq

Reputation: 193261

is there someway that i can use a service globally?

You can simply expose service as the $rootScope property so it will be available in every template:

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
  $rootScope.authFactory = authFactory;
}]);

Upvotes: 2

Related Questions