Quick summary
A well written directive that is extendable and/or interacts with other directives will have a controller. That controller needs to access the DOM because it is where that directive’s functionality is defined. Directives are effectively a different way to bind a controller/scope to an element on the page; the preferred way to add functionality to the DOM. From what I understand, the best practice is: don’t use both a controller and a link function. So directive controllers need an $element.
Detail answers
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?
The guides are a little misleading once you dig into how it all works.
what the guides say:
Controllers handle defining functions and assign variables to be used by the view. And the right way to bind those functions and variables to the view is with a directive. That is my understanding of best practices, having worked with large and growing angular applications for the past year.
why it is confusing:
The tricky thing is that the directive basically binds a controller to the DOM. ng-model is a directive and has a controller that can be accessed from other directives. You will want to take advantage of this if you do things like add custom validation fanciness. This controller of the directive is supposed to manipulate the DOM. So a generic controller is actually is a super set of view controllers; a detail that the tutorials usually glaze over.
Is there any non-hacky use case for this?
‘correct’ ways of using $element:
Using it in a directive’s controller for example.
Are there any examples of this being used in available code somewhere?
Examples:
Angular source code, though perhaps a little dense of a read, is good code and well commented. It may take a little bit to see what’s going on, but usually quite informative.
NgModelController (complex example)
https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js
https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1660
What could be a simple example, but uses a compile function instead, the eventDirectives (ng-click for example),
https://github.com/angular/angular.js/blob/master/src/ng/directive/ngEventDirs.js#L3