0

I have a variable that is defined globally, and I need it in an angular expression.
I tried using the $window service but it doesn't seem to work:

JS

var INCLUDE_FILENAME = 'includeme.html';

HTML

{{$window.INCLUDE_FILENAME}}
<div data-ng-include="$window.INCLUDE_FILENAME"></div>

Above code available as a plunkr

I know that I could use a controller storing data from $window as a scope variable, but that's rather useless as I could just access it without the angular service in that case.

3
  • I don't think you can really do this, or even that you should do this. You can add INCLUDE_FILENAME to the scope... Commented Aug 13, 2014 at 20:24
  • You cannot directly access global variables as angular bindings. One way you can do is this way plnkr.co/edit/2fXu3s?p=preview Commented Aug 13, 2014 at 20:25
  • @ExplosionPills I agree this shouldn't be done. Unfortunately, if the variable needed is only made available in the global scope, there isn't much choice. Commented Aug 13, 2014 at 21:06

1 Answer 1

1

You cannot directly access global variables as a part of angular bindings in the view, since they are evaluated against the scope, in your case $rootScope. So basically you could add a function to the $rootScope on run of the app.

Example:-

angular.module('app',[]).run(['$rootScope', '$window', 
     function($rootScope, $window){
       $rootScope.getGlobals = function(variableName){
       return $window[variableName];
     };
}]);

and access it via this method anywhere on any scope, since any child scopes (except for isolated scopes) are descendants of $rootScope this method will be available to them.

<h1>Loading below...</h1>
{{getGlobals('INCLUDE_FILENAME')}};
<div data-ng-include="getGlobals('INCLUDE_FILENAME')"></div>

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure what's the purpose of the $window service then - couldn't it just be replaced by window in your code?
@Razor You could. It is dependency injection. You cannot inject window but you could only inject $window. It has been added for testability... But the basic idea is that you cannot use global variables in the templates expecting that angular will evaluate it.. Well it is right here documented

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.