最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Differences between document vs $document in Angular - Stack Overflow

programmeradmin9浏览0评论

What are the differences between using document and $document while developing Angular's applications? I read that it's better to use angular's equivalents like: $window instead of window or $timeout instead of setTimeout.

But... why? I thought window, setTimeout and document are faster because they are native and doesn't need to "pass through" code of Angular framework.

Is it better to use Angular's equivalents instead of native functions, objects from JS?

What are the differences between using document and $document while developing Angular's applications? I read that it's better to use angular's equivalents like: $window instead of window or $timeout instead of setTimeout.

But... why? I thought window, setTimeout and document are faster because they are native and doesn't need to "pass through" code of Angular framework.

Is it better to use Angular's equivalents instead of native functions, objects from JS?

Share Improve this question edited Oct 27, 2015 at 8:54 justcurious 8555 gold badges12 silver badges31 bronze badges asked Oct 27, 2015 at 8:31 JDoJDo 1231 silver badge5 bronze badges 3
  • Absolutely agree with you.. Yes the native code is faster but the reason I understand is that the new angular developer after you may not understand the native code.. That's why, probably. But I wonder why (or precisely how) people learn Angular without knowing what happens in native code? – Akshay Khandelwal Commented Oct 27, 2015 at 8:34
  • Look what angularJS docs states: A jQuery or jqLite wrapper for the browser's window.document object. – Muhammad Faizan Khan Commented Oct 27, 2015 at 9:55
  • coderwall./p/udpmtq/angularjs-use-timeout-not-settimeout this will help u – Muhammad Faizan Khan Commented Oct 27, 2015 at 9:55
Add a ment  | 

4 Answers 4

Reset to default 9

By using the angular services for $document and $window you make your code unit test ready. This dependency injection allows you to use mock versions of $document or $window in your tests.

The performance impact mentioned can be ignored.

$document is a jQuery object, $(document).

So basically you should be able to do:

$document[0].property = document.property

You can look at this for an example.

Following is always true: $window.document === $document[0]

You should use angular wrapers, bcus it doesn't break the angular synchronization with model->view,

For exmaple, if you use setTimeout you will have to $digest() the scope to refresh the values in the view, if you plan on changing some model values, on the other hand if you use $timeout you don't need to do it bcus the scope will refresh after the function ends

发布评论

评论列表(0)

  1. 暂无评论