Show / Hide Table of Contents
Close
Loading …
There was an error loading this resource. Please try again later.
 Improve this Doc  View Source

$window

  1. - service in module ng
Contents

Overview

A reference to the browser's window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In AngularJS we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Expressions, like the one defined for the ngClick directive in the example below, are evaluated with respect to the current scope. Therefore, there is no risk of inadvertently coding in a dependency on a global value in such an expression.

Example

<script>
  angular.module('windowExample', [])
    .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
      $scope.greeting = 'Hello, World!';
      $scope.doGreeting = function(greeting) {
        $window.alert(greeting);
      };
    }]);
</script>
<div ng-controller="ExampleController">
  <input type="text" ng-model="greeting" aria-label="greeting" />
  <button ng-click="doGreeting(greeting)">ALERT</button>
</div>