Search code examples
javascripthtmlangularjsrootscope

How to pass variables into $rootScope from backend


I need to pass some variables from backend to Angular frontend in HTML code. Ideally, I like to have it within $rootScope. However, $rootScope is not defined yet when the page is loaded. The only way I can do it is:

var myVar = ["aa", "bb"];

Then get it from $window.myVar

So is there a way to wait until $rootScope is defined by Angular and then parse value into it within HTML?


Solution

  • How about defining a constant and injecting it where you need it?

    angular.module('yourModule').constant('yourVar', ['aa', 'bb']);

    Then you can use it in the run stage:

    angular.module('yourModule').run(function($rootScope, yourVar) {
        $rootScope.yourVar = yourVar;
    });