3

My code has the following:

var app = angular.module('app', ['admin', 'home', 'questions', 'ui.compat', 'ngResource', 'LocalStorageModule']);

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

Can someone please explain what the two lines starting with $rootScope are doing. Are they needed?

3 Answers3

3

This comment is taken from example source code on projects github page:

It's very handy to add references to $state and $stateParams to the $rootScope so that you can access them from any scope within your applications. For example, <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li> to active whenever 'contacts.list' or one of its decendents is active.

You can check it out here.

Tomas Petovsky
  • 285
  • 4
  • 14
1

I don't think this is standard code. The only reason i see these being added to you rootScope it to facilitate binding within the html view everywhere. Else if you want to bind to some property of either $state or $stateParams you would have to inject the $tate and $stateParams service into the controller. Ideally this should be injected into controllers that require this service.

If you remove it any html binding dependent on it would fail. Search html views for bindings with name $state and $stateParams and you would find where they are used.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • okay so if these lines are present then would those states be available anytime I do {{ $state }} without me having to redefine $scope.$state = $state in each controller ? –  Sep 02 '13 at 12:21
  • Yes, i believe so. But better to do explicitly, as it makes your dependencies clear. – Chandermani Sep 02 '13 at 12:24
0

its so you can pass $state and $stateParams values into your root Controller and be able to access them

example use: ng-click="$state.transitionTo('stateName', $stateParams)"

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#note-about-using-state-within-a-template