Jack Ryan
Jack Ryan

Reputation: 1318

Access variable from router in Angular

I am working on a web application with Angular. I have created a header that is included in the index.html, so it is fixed to every page and the content of the page is injected through a ui-view. My question is: if I want to only show this header after the user has passed the signup and login pages, what should I do?

I have added a variable to my router as shown below, but I am not sure how to access the router's variable from the index.html, as it is not attached to a controller (since it is fixed content across all pages). I intended to simply throw an ng-hide="hideHeader" in the index.html.

app.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/login');

$stateProvider
    .state('login', {
        url: '/login',
        templateUrl: 'app/views/login/login.html',
        controller: 'loginController',
        controllerAs: 'vm',
        hideHeader: true
    })

    .state('signup', {
        url: '/signup',
        templateUrl: 'app/views/signup/signup.html',
        controller: 'signupController',
        controllerAs: 'vm',
        hideHeader: true
    })

    .state('landing', {
        url: '/landing',
        templateUrl: 'app/views/landing/landing.html',
        controller: 'landingController',
        controllerAs: 'vm',
        hideHeader: false
    })

    .state('account-management', {
        url: '/account-management',
        templateUrl: 'app/views/account-management/account-management.html',
        controller: 'accountManagementController',
        controllerAs: 'vm'
        hideHeader: false
    });
});

How can I access this hideHeader value from the index.html? Is there a way to set a global scope variable and get the value from there?

Upvotes: 0

Views: 87

Answers (1)

Akshay Dhalwala
Akshay Dhalwala

Reputation: 838

Here's a different approach: Create a service specifically for authentication (login/logout) and authentication status. Then just call that service in your header. Given that the header is dependent on your authentication, then it makes sense to abstract that away. Your login/signup controllers will interact with this service.

Your routes can now also call this service to see if they should allow the user to view them based on login status.

Upvotes: 3

Related Questions