Michael R
Michael R

Reputation: 1607

Why does $compileProvider have a directive method?

I observe from the Angular documentation, that $compileProvider has both a directive() and component() method. See: https://docs.angularjs.org/api/ng/provider/$compileProvider

I also observe the usage of that directive in the docs https://docs.angularjs.org/api/ng/service/$compile

Search for: 'compileExample'

But I don't see any explanation of the purpose.

Questions

Q) Why does $compileProvider have a directive method? What's the purpose or benefit?

Q) How is registering a directive with the compiler different from declaring a directive on a module?

Upvotes: 3

Views: 2281

Answers (2)

Carsten Führmann
Carsten Führmann

Reputation: 3490

The AngularJS guide, on https://docs.angularjs.org/guide/module, states:

angular.module('myModule', []).
  value('a', 123).
  factory('a', function() { return 123; }).
  directive('directiveName', ...).
  filter('filterName', ...);

// is same as

angular.module('myModule', []).
  config(function($provide, $compileProvider, $filterProvider) {
    $provide.value('a', 123);
    $provide.factory('a', function() { return 123; });
    $compileProvider.directive('directiveName', ...);
    $filterProvider.register('filterName', ...);
  });

So we know at least the $compileProvideris to directives what $provideris to factories.

There is at least one important use case for $compileProvider: to mock directives in unit tests. To see this, check out the answer by Sylvain to this StackOverflow question: How do you mock directives to enable unit testing of higher level directive?.

Upvotes: 0

georgeawg
georgeawg

Reputation: 48968

How is registering a directive with the compiler different from declaring a directive on a module?

The module loader uses the $compileProvider.directive() method to load directives:

AngularJS Module Loader Source Code

/**
   * @ngdoc method
   * @name angular.Module#directive
   * @module ng
   * @param {string|Object} name Directive name, or an object map of directives where the
   *    keys are the names and the values are the factories.
   * @param {Function} directiveFactory Factory function for creating new instance of
   * directives.
   * @description
   * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
   */
  directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),

The difference is that the module loader is capable of decorating directives and does it before the config phase. I have not found a use case for adding directives during the config phase.

Upvotes: 1

Related Questions