Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
Marc Rasmussen Avatar asked Mar 31 '26 08:03

Marc Rasmussen


1 Answers

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;
}]);
like image 64
dfsq Avatar answered Apr 02 '26 22:04

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!