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.

Razor
  • 27,418
  • 8
  • 53
  • 76
  • I don't think you can really do this, or even that you should do this. You can add `INCLUDE_FILENAME` to the scope... – Explosion Pills Aug 13 '14 at 20:24
  • You cannot directly access global variables as angular bindings. One way you can do is this way http://plnkr.co/edit/2fXu3s?p=preview – PSL Aug 13 '14 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. – Razor Aug 13 '14 at 21:06

1 Answers1

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

PSL
  • 123,204
  • 21
  • 253
  • 243
  • 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 Aug 13 '14 at 20:46
  • 1
    @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](https://docs.angularjs.org/api/ng/service/$window) – PSL Aug 13 '14 at 20:47
  • http://stackoverflow.com/questions/25299436/unable-to-call-object-keys-in-angularjs/25299523#25299523 – PSL Aug 15 '14 at 03:35