【问题标题】:Dependency injection in Angular Components like directivesAngular 组件中的依赖注入,如指令
【发布时间】:2016-09-14 01:45:30
【问题描述】:

这是我习惯使用角度指令的一件事

angular.module('app.directives').directive('login', ['$templateCache', function ($templateCache) {
    return {
        restrict: 'E',
        template: $templateCache.get('directives/login/login.html'),
        controller: 'LoginController as vm',
        scope: true
    };
}]);

我已经非常喜欢使用 模板缓存 在我的指令模板中注入 HTML 内容。现在有了 Angular 1.5,所有酷孩子都在使用这个新东西,叫做 component()在组件本身中注入东西(而不是在控制器中)?

在这种情况下,您可以看到我将 $templateCache 依赖项注入到 login 指令中。我将如何将此指令重写为组件? (记住我希望在 templateUrl 上使用 $templateCache)

【问题讨论】:

    标签: javascript angularjs angularjs-components


    【解决方案1】:

    嗯,在 Angular 1.5 组件中,template 属性可以是一个函数,并且这个函数是可注入的 (documentation)。

    所以,你可以使用类似的东西:

    ...
    template: ['$templateCache', function ($templateCache) {
       return $templateCache.get('directives/login/login.html')
    }]
    ...
    

    来自 google 搜索的几个链接:one 和 two。

    希望它会有所帮助。

    【讨论】:

      【解决方案2】:

      MaKCblMKo 的回答是对的,但请记住,AngularJS 会先检查 templateCache,然后再去检索模板。因此,您不必在指令或组件中进行此调用。

      angular.module('myApp', [])
      .component('myComponent',{
          templateUrl: 'yourGulpPattern'
      })
      .run(function($templateCache) {
          $templateCache.put('yourGulpPattern', 'This is the content of the template');
      });
      

      https://jsfiddle.net/osbnoebe/6/

      【讨论】:

      • 这不是把内容放在那里,我有一个 gulp 任务,可以缩小并“放入”模板缓存中的每个 HTML 文件。我只需要访问该元素,以便检索它的内容。
      • 这很酷,但我想说的是,如果您的 gulp 任务执行“放置”,那么您仍然不需要触摸 $templateCache。只需引用 url,它就会从缓存中获取它,因为它已经存在。我的 put 示例只是表明它已经在缓存中。换句话说 - 假设我的示例中的 run 函数是你的 gulp 任务......除非我仍然不明白你在说什么。
      • 只需引用 templateUrl 并让 Angular 为您从 $templateCache 中提取它。我希望这更清楚。我并不是想向您展示如何将其放入缓存中。
      • 我尝试了你的方法,我得到了 404。实际上,我的服务器没有在使用 templateUrl 所需的路径中提供页面,而是 gulp 只是用预定义的模式填充 templateCahce我可以使用 $templateCache.get.
      • 我仍在解决这个问题,因为虽然我接受的答案确实回答了我的问题,但你的方式更干净,我更喜欢它。幸运的是,我最终发现了一个完全不相关的问题,这让我相信你的方法不起作用。现在我按照你说的那样工作了,而且非常整洁。
      猜你喜欢
      • 2014-11-21
      • 2015-08-28
      • 1970-01-01
      • 2016-09-15
      • 2016-09-10
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2017-05-24
      相关资源
      最近更新 更多