Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component access ui-router $state

Using the new .component() method introduced in Angular 1.5.x and AngularUI Router 1.0-alpha, how can I access the current router state from inside a component?

For example (i'm using ES2015 here and follow Todd Motto's Angular Styleguide):

import angular from 'angular';

const header = angular
    .module('header', [])
    .component('header', {
        template: `
            <p>{{$state.current.name}}</p>
        `
    });

Note: header is a child component, ui-router is injected and configured in a parent component.

But $state.current.name or even simply $state doesn't display anything in the component's template.

The global idea of what I'm trying to do is setting a class on the header depending on the current state of the application.

I've tried to set the state on $rootScope but it doesn't work either... I'm probably missing something since I'm quite new to Angular, so maybe someone has an idea?

like image 914
ClementParis016 Avatar asked May 08 '26 07:05

ClementParis016


1 Answers

You inject it to the controller:

import angular from 'angular';

const header = angular
    .module('header', [])
    .component('header', {
        template: `
            <p>{{$ctrl.$state.current.name}}</p>
        `,
        controller: ['$state', function($state) {
            this.$state = $state;
        }]
    });

Do note the $ctrl in the template!

like image 193
Nikos Paraskevopoulos Avatar answered May 11 '26 01:05

Nikos Paraskevopoulos