【问题标题】:Why does $compileProvider have a directive method?为什么 $compileProvider 有一个指令方法?
【发布时间】:2017-06-21 07:35:56
【问题描述】:

我从 Angular 文档中观察到,$compileProvider 同时具有 directive()component() 方法。看: https://docs.angularjs.org/api/ng/provider/$compileProvider

我还观察了文档中该指令的用法 https://docs.angularjs.org/api/ng/service/$compile

搜索:'compileExample'

但我没有看到任何关于目的的解释。

问题

Q) 为什么 $compileProvider 有一个指令方法?目的或好处是什么?

Q) 向编译器注册指令与在模块上声明指令有何不同?

【问题讨论】:

    标签: 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?

      【讨论】:

        猜你喜欢
        • 2015-05-28
        • 2011-08-29
        • 2014-09-25
        • 2013-04-13
        • 2016-03-06
        • 1970-01-01
        • 2015-10-15
        • 2022-01-02
        • 2017-10-24
        相关资源
        最近更新 更多