$window
-
ng
模塊中的服務
這是一個瀏覽器端 window
對象的引用. 由于Javascript 中的window
是一個全局變量,它會給可測試性帶來問題。在Angular中我們總會通過 $window
服務來引用它,因此在測試總它可以被改寫、刪除或模擬。
在下面的例子中,表達式可以像定義一個ngClick
指令一樣,在當前作用域被嚴格的評估。因此, 在這種依賴于一個全局變量表達式中,不會因為不經意的編碼而帶來風險。
例子
html and javascript
<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>
protractor
it('should display the greeting in the input box', function() {
element(by.model('greeting')).sendKeys('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
$document
-
ng
模塊中的服務
一個對于瀏覽器中的 window.document
對象的jQuery 或 jqLite 封裝。
依賴
$window
例子
html
<div ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>
javascript
angular.module('documentExample', [])
.controller('ExampleController', ['$scope', '$document',
function($scope, $document) {
$scope.title = $document[0].title;
$scope.windowTitle = angular.element(window.document)[0].title;
}]);