【问题标题】:Why does $compileProvider have a directive method?为什么 $compileProvider 有一个指令方法?
【发布时间】:2017-06-21 07:35:56
【问题描述】:
【问题讨论】:
标签:
angularjs
angularjs-directive
【解决方案1】:
向编译器注册指令与在模块上声明指令有何不同?
module loader 使用$compileProvider.directive() 方法加载指令:
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'),
不同之处在于模块加载器能够装饰指令并在配置阶段之前完成。我还没有找到在配置阶段添加指令的用例。
【解决方案2】:
https://docs.angularjs.org/guide/module 上的 AngularJS 指南指出:
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', ...);
});
所以我们至少知道 $compileProvideris 是指 $provideris 是工厂的指令。
$compileProvider 至少有一个重要的用例:在单元测试中模拟指令。要查看这一点,请查看 Sylvain 对此 StackOverflow 问题的回答:How do you mock directives to enable unit testing of higher level directive?。