ClementParis016 ClementParis016 - 4 months ago 25
AngularJS Question

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?

Answer

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!