当前位置:/AngularJS API/ng/服务(service)/$window

ng

一个浏览器窗口对象的引用。它是一个全局对象,在window中是全局可用的,但是它导致一些问题。在Angular中也经常通过$window服务提到它,因此它可以被重写、删除及测试。

$window 等同于 window。

$window对象可以用来获取浏览器窗口各项属性(如窗口高度宽度、浏览器版本等等)。


实例

<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>
it('should linkify the snippet with urls', function() {
  expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
      toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
           'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
});

it('should not linkify snippet without the linky filter', function() {
  expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
      toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
           'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
});

it('should update', function() {
  element(by.model('snippet')).clear();
  element(by.model('snippet')).sendKeys('new http://link.');
  expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
      toBe('new http://link.');
  expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
      .toBe('new http://link.');
});

it('should work with the target property', function() {
 expect(element(by.id('linky-target')).
     element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
     toBe('http://angularjs.org/');
 expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
});

it('should optionally add custom attributes', function() {
 expect(element(by.id('linky-custom-attributes')).
     element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
     toBe('http://angularjs.org/');
 expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
});