Accessing values in the $rootScope from outside angular

14 Jul 2016

In order to pass a value to Angular in an Angular way, you have to use constant or value methods. By doing that you can use Angular's dependency injection to inject the required values to any directive or controller or factory.

window.culture = "en"; // Vanilla Javascript object

var app = angular.module("myApp", []);

//Angular Way
app.constant('pageCulture', 'en');
//OR
app.value('pageCulture', 'en');

//Later you can inject and consume the values in any angular components using it as a dependency

app.controller('myController', myController);

myController.$inject = ['pageCulture'];

function myController(pageCulture)
{
    
}

In few cases, where you use angular for the SPA like functionality within a page and latter want to pass that to a Vanilla JavaScript function outside AngularJS. For this, get jQLite object of the bootstrapped element and then use the injector and get the "rootscope"

app.controller('myController', myController);

myController.$inject = ['$rootScope'];

function myController($rootScope){
   $rootScope.myOutput = 2*2;
}

//You can access the values assigned to the routescope like below 
//[That is by querying the injector of the bootstrapped element - here it is document object]
angular.element(document).injector().get('$rootScope').myOutput