I have seen the following:
angular.bootstrap(document, ['TodoApp']);
angular.bootstrap(angular.element("body")[0], ['TodoApp']);
Also the AngularJS documentation mentions this which I don't really understand.
angular.element(document).ready(function() {
angular.bootstrap(document);
});
Is there any difference between these methods? In particular what is the last method from the Angular docs doing? Is one any better to use than the other?
Answer
They are roughly the same, with a few differences:
angular.bootstrap(document, ['TodoApp']);
This will work if you have your scripts loaded at the end of the page (instead of in the header).
Otherwise, the DOM will not be loaded at the time of bootrsaping the app (there won't be any template to be compiled, the directives won't have any effect).
This one works: plnkr
This one doesn't: plnkr
angular.bootstrap(angular.element("body")[0], ['TodoApp']);
The same as before, using body
as the root of the application. It uses a selector that is not available in jqLite, so you need to have full jQuery included in the app.
I'm not sure what is the advantage of using body
instead document
, but probably has something to do with e2e testing, as explained in this comment
angular.element(document).ready(function() {
angular.bootstrap(document);
});
This one actually waits for the DOM to be loaded, so it will work even if you include your scripts in the header.
This is basically the same as jQuery's $(document).ready(
, but using jqLite
's angular.element
.
In the last example, no modules are being passed to the bootstrap function, most likely you will need to declare your main module, unless your app consists only on controllers in the global namespace.
So the last option will be like the following, in order to be similar to the other two:
angular.element(document).ready(function() {
angular.bootstrap(document, ['TodoApp']);
});
I guess that most of the time the safest bet is using this last approach.
No comments:
Post a Comment