Working With Global Variables In AngularJS

Consider the following Angular code:

  <script data-require="angular.js@1.3.15" data-semver="1.3.15" src=""></script>
  <script type="text/javascript">
    var globalVariable = "one";
    window.windowVariable = "two";

<body ng-app="example">
      Global Variable: <strong>{{ globalVariable }}</strong>
      Window Variable: <strong>{{ windowVariable }}</strong>

The output might surprise you.

Output of Example

Both variables are undefined. The key here is how Angular interprets the expressions between the curly braces. You might expect Angular to do a simple eval on the code, but that is not the case - Angular actually uses JavaScript to parse these JavaScript-like syntax within the context of the current scope.

This means we can’t simply access global variables or variables on window in these expressions. There might be scenarios where you want to do exactly that - for example, feature flags are often rendered server-side and attached directly to window (or rendered as global variables).

In order to access these inside template expressions you need to assign them to the scope.

app.controller "ExampleController", ($scope, $window) ->
  $scope.globalVariable = globalVariable
  $scope.windowVariable = $window.windowVariable

You can find all the code on Plunker. Happy coding.