11

Hello I am trying to manually bootstrap an angular app, but there is some business that needs to be taken care of first.This article mentions the technique I am interested in.

when I inject this:

 var $injector = angular.injector(["ng"]);
 var $http = $injector.get("$http");

it works fine, but this:

var $injector= angular.injector(["ng", "myApp"]);
var $location = $injector.get("$location");

Throws the following error.

Uncaught Error: [$injector:unpr] Unknown provider: $rootElementProvider <- $rootElement <- $location <- $location

Is it possible to get $location prior to angular.bootstrap?

Thanks a ton!

PSL
  • 123,204
  • 21
  • 253
  • 243
Jeremythuff
  • 1,518
  • 2
  • 13
  • 35

2 Answers2

14

In order to get the $location before bootstrapping, you would basically need to provide the $rootElement. One way is to mock it: inject ngMock module from angular-mocks to get the injector.

var $injector= angular.injector(['ng','ngMock',"plunker"]);
var $location = $injector.get("$location");

Plunker

Or supply rootElement on your own by creating a mock app and including that while getting the injector.

var mockApp = angular.module('mockApp', []).provider({
  $rootElement:function() {
     this.$get = function() {
       return angular.element('<div ng-app></div>');
    };
  }
});

var $injector= angular.injector(['ng','mockApp',"plunker"]);

var $location = $injector.get("$location");

Plunker

Or other way (based on your feasibility) is to obtain the location from the window using window.location.

Also worthwhile noting this thread on github

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
PSL
  • 123,204
  • 21
  • 253
  • 243
  • This does answer my question, but did not solve my problem. One of the things I needed from location was the .search method, and location seems to be in a odd state when injected in this way, and the object is returned empty. – Jeremythuff Feb 09 '15 at 05:54
  • Why dont i just use window.location.search? What is ur ultimate aim. – PSL Feb 09 '15 at 06:29
  • I ended up doing just that. There are some factories in our app that innect $location and we needed their functionality pre-bootstrap. I was trying to avoid having duplicate code by using those services. – Jeremythuff Feb 09 '15 at 07:12
4

root element must be in inserted in document. See http://plnkr.co/edit/OrgStgw4NpjU2LcIFXsB

var rootElement = angular.element(document);

var mockApp = angular.module('mockApp', []).provider({
  $rootElement:function() {
     this.$get = function() {
       return rootElement;
    };
  }
});
Matjaz Lipus
  • 702
  • 1
  • 5
  • 10