How to access global js variable in AngularJS directive

windweller picture windweller · Oct 15, 2013 · Viewed 101.1k times · Source

First of all, I checked and I didn't find any article covering my question.

How to access a pre-defined js global variable in angularJS built-in directive?

For example, I define this variable in <script>var variable1 = true; </script>

Then I write a AngularJS directive:

<div ng-if="variable1">Show some hidden stuff!</div>

This does not really work.

Then I'm informed that I should use ng-init

So I wrote code somewhere else like:

<div ng-init = "angularVariable1 = variable1"></div>

And this apparently does not work as well...this is like a vicious cycle. You need to access pre-defined js global variables, then you need to use ng-init; in order to use ng-init, you need to access global variables.

Any particular way to do this?

Answer

Adam Thomas picture Adam Thomas · Oct 15, 2013

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);