2

I would like to do $state.reload() in my angular application for debugging purpose. See this related question how-do-i-reload-an-angular-partial-for-testing-purpose

However, I am not able to capture the $state in my application which doesn't even have the $rootScope object exposed? I managed to get the $rootScope by doing this as shown in how-to-access-update-rootscope-from-outside-angular

var $body = angular.element(document.body);
var $rootScope = $body.scope().$root; 

And then as explained in the Wiki

var myApp = angular.module('myApp', []);
angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});

But this not setting anything to $rootScope.$state thought $rootScope is accessible now. Any help? I'm using Angular 1.3.x.

Edit: Even this doesn't work,

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    console.log("Testing");
});
Nishant
  • 20,354
  • 18
  • 69
  • 101
  • Problem is that it doesn't event `run`? – Nishant Sep 29 '17 at 17:37
  • 1
    The last snippet obviously doesn't work because of some error. If you're getting a problem, it's always desirable to provide full error message and http://stackoverflow.com/help/mcve , otherwise problem solving becomes total guesswork. Any way, in your case `$rootScope.$state = $state` is a hack that is not necessary. It should be just `angular.element(document.body).injector().get('$state')`. – Estus Flask Sep 29 '17 at 20:12
  • Ok, I don't see a traceback related to this but there is something else that is being done which fails - can't relate it to this. But it is fine. Will debug it sometime later. I can see that `run` does a `push` so it doesn't happen synchronously maybe :) – Nishant Sep 30 '17 at 08:41

2 Answers2

4

Considering that AngularJS application was bootstrapped on body, it should be possible to get service instance with

angular.element(document.body).injector().get('$state');

There is no need to expose it to scope.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

For angular 1.5.x - 1.6.x

You need to install this https://github.com/olov/ng-annotate, after that your code should looks like this

angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
    'ngInject'; // this will fix dependency injection
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
});
Daniel Rosenberg
  • 600
  • 6
  • 11