Why is $element available/injected in controller?

Viewed 52161

In AngularJS, I've noticed that a controller is injected with $element, which is a JQuery/JQLite wrapper of the element the controller is controlling. For example:

<body ng-controller="MainCtrl">

Then you can have access to the body element in the controller by injecting $element

app.controller('MainCtrl', function($scope, $element) { ...

This can be seen working at this Plunkr.

And seems to be confirmed as a deliberate feature in the docs for $compile

My questions are:

  • In the light of the various guides and tutorials that suggest you shouldn't access the DOM in a controller, why is this even possible?

  • Is there any non-hacky use case for this?

  • Are there any examples of this being used in available code somewhere?

Thanks.

4 Answers
Related