ClementParis016 ClementParis016 - 1 year ago 127
AngularJS Question

Angular 1.5 component access ui-router $state

Using the new

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: `

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

or even simply
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
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 Source

You inject it to the controller:

import angular from 'angular';

const header = angular
    .module('header', [])
    .component('header', {
        template: `
        controller: ['$state', function($state) {
            this.$state = $state;

Do note the $ctrl in the template!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download