【问题标题】:What's the difference between $document and $window.document in Angular?Angular 中的 $document 和 $window.document 有什么区别?
【发布时间】:2015-01-24 00:04:31
【问题描述】:

我在JSBin中尝试了以下代码,第一个可以获取canvas对象。但是,第二个不能。

JSBin:http://jsbin.com/natavejasa/1/edit?html,js,output

var canvas = $window.document.getElementById('myCanvas');

JSBin:http://jsbin.com/yareb/1/edit?html,js,output

var canvas = $document.getElementById('myCanvas');

所以我想知道$window.document$document 之间有什么区别。

【问题讨论】:

    标签: javascript angularjs canvas


    【解决方案1】:

    $document 等价于 angular.element(window.document) - window.document 的 jqLit​​e 包装器。

    $window.documentwindow.document 相同 - 即它是 DOM 元素 document

    以下是true

    $window.document === $document[0]
    

    【讨论】:

      【解决方案2】:

      $document 是一个 Angular 服务,它引用浏览器的 window.document 对象。

      <script>
         var app = angular.module('documentExample', []);
           app.controller('ExampleController', ['$scope', '$document', function ($scope,$document) {
                    $scope.title = $document[0].title;
                    $scope.windowTitle = angular.element(window.document)[0].title;
              }]);
       </script>
      
      <div ng-app="documentExample" ng-controller="ExampleController">
         <p>$document title: <b ng-bind="title"></b></p>
         <p>window.document title: <b ng-bind="windowTitle"></b></p>
      </div>
      
      • $window.document 和 window.document 一样

      【讨论】:

        【解决方案3】:

        这并没有什么不同,就像你从关卡中看到的一样。这不是 angularjs 它是 js,但你需要删除第一美元。 从 angularjs 很难说。如果可能的话,你需要使用简单的 js。 这些实体是全球性的。

        【讨论】:

        • 是的,它是不同的。阅读@New Dev 的上一个答案
        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2013-01-08
        • 2011-07-08
        • 1970-01-01
        • 2012-01-13
        • 1970-01-01
        • 2018-11-18
        相关资源
        最近更新 更多