$window, $document

$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;

}]);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容