Add reference to $state and $stateParams to $rootScope in Typescript (angular)

10,926

Solution 1

UPDATE: previous version of this answer would not be working with a angular strict mode, or minification.

I would therefore suggest to add this ng-strict-di directive into index.html:

<html data-ng-app="App" ng-strict-di> // see ng-strict-di
  <head>

And that would reveal that the proper way is:

module App
{
    export class RootConfig
    {
        static inject = ['$rootScope', '$state', '$stateParams'];

        constructor(
            $rootScope: any, //ng.IRootScopeService,
            $state: ng.ui.IStateProvider,
            $stateParams: ng.ui.IStateParamsService)
        {
            $rootScope.$state = $state;
            $rootScope.$stateParams = $stateParams;
        }
    }
}

angular.module('App')
    // wrong - not working in minified world
    // .run(App.RootConfig);
    // correct
    .run(['$rootScope', '$state', '$stateParams', App.RootConfig]);

Why this $rootScope: any, //ng.IRootScopeService, instead of this: $rootScope: ng.IRootScopeService,? To make life easier... and quickly assign not declared properties $state and $stateParams

Solution 2

I found a cleaner route than setting it to any

declare module app {
    interface IScope extends ng.IScope {
        $root:IRootScopeService
    }

    interface IRootScopeService extends ng.IRootScopeService {
        $state:ng.ui.IStateService
    }
}

Then to use it just declare like

constructor(
        $rootScope: app.IRootScopeService,
        $state: ng.ui.IStateProvider
{
    $rootScope.$state = $state;
}
Share:
10,926
xvdiff
Author by

xvdiff

Updated on July 12, 2022

Comments

  • xvdiff
    xvdiff almost 2 years

    I'm trying to set the page title of my angular app based on data of the current state (configured in ui-router).

     <title ng-bind="$state.current.data.pageTitle></title>
    

    On this link, I found the following to add a reference to $state/$stateParams to the root scope:

    .run([ '$rootScope', '$state', '$stateParams',
        function ($rootScope, $state, $stateParams) {
            $rootScope.$state = $state;
            $rootScope.$stateParams = $stateParams;
        }])
    

    How can I translate this to typescript?

     function run($rootScope: ng.IRootScopeService, $state : ng.ui.IState, $stateParams : ng.ui.IStateParamsService) {
        $rootScope.$state // 'state' cannot be resolved
    }