I'm not sure why you got down-voted on this as I think it's a relevant question about one of the less clear aspects of angular 1.x.
exposing directive APIs
One of the prime reasons to set up a directive with a controller is to expose a directive's API to other directives. A good example of this is ngModel
and the ngModelController
. Many custom directives need access to the ngModel
that's also declared on or above where the custom directive is declared. You see this in the directive definition via:
{ require:'^ngModel' }
This is actually saying this custom directive needs to access the APIs available on the ngModelController
to do additional work. For instance, you want a directive to do some custom parsing or formatting on a particular ngModel. In my app, I kept getting errors for date strings that came back from the server. I created this custom directive to handle the error and format the string properly (this is coffeescript btw):
.directive 'dateString', [
()->
{
priority: 10
require: 'ngModel'
link: ($scope, elem, attrs, ngModel)->
ngModel.$formatters.push (val)-> new Date(val)
}
]
If there were no ngModelController
, I would not have access to the APIs to add a new formatter function.
So in conclusion, we might create directive controllers to provide APIs for other directives that may operate on the same UI element.
classic controller role
In order to be within the spirit and intent of Angular, using a controller to expose APIs to the template is better than trying to use a jquery implementation. In other words, it's better to do this:
directive w. controller
controller: function($scope){
$scope.doSomething = function(){ ... }
},
template: '<div><button ng-click="doSomething()">Click Me</button></div>'
vs something like this
directive w. jquery-like implementation
link: function($scope, elem, attrs){
elem('button').bind('click', function(){ ... })
},
template: '<div><button>Click Me</button></div>'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…