Mastering Web Application

(Rick Simeone) #1
Chapter 9

Or it can be a constructor function that will be used to instantiate the controller:


myModule.directive('myDirective', function() {
return {
controller: function($scope, ...) { ... }
};
});

If the controller is defined on a module then it is easy to test it
independently of the directive. But this also means that the controller
is exposed to the whole application, via the injector, so you must
be careful that its name does not conflict with controllers in other
modules of the application.
Defining the module inline, as an anonymous function, makes it
more difficult to test it separately from the directive but allows us to
keep it private to the directive.

Injecting special dependencies into directive controllers


Just like any controller, directive controllers are injected with dependencies by
AngularJS. All controllers are injected with $scope and you can specify other
services to be injected, such as $timeout or $rootScope. On top of these, directive
controllers can also be injected with the following three special services:



  • $element: This is a reference to the directive's DOM element. This will be
    wrapped in jQLite/jQuery.

  • $attrs: This is a normalized list of the attributes that appear on the
    directive's DOM element.

  • $transclude: This is a transclusion function that is already bound to the
    correct scope. This function is described in the transclusion functions.

Free download pdf