Working With Global Variables In AngularJS

Consider the following Angular code:

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

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

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.