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
4 Answers
Reset to default 9By 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