【问题标题】:Angular 1.5 component dependency injectionAngular 1.5 组件依赖注入
【发布时间】:2016-09-10 20:36:24
【问题描述】:

我一直在尝试在项目中使用新的 Angular 1.5 component 语法,但我不知道如何将依赖项注入到组件定义中。

这是我将现有指令重构为组件的尝试:

angular
    .module('app.myModule')
    .component('row', {
      bindings: {
        details: '@',
        zip: '@'
      },
      controller: 'RowController',
      templateUrl: basePath + 'modules/row.html' // basePath needs to be injected
    })

出于各种原因,我们将常量 basePath 作为 templateUrl 的一部分注入到所有指令中。

由于组件定义不是函数,我如何在组件上执行此操作?

【问题讨论】:

    标签: angularjs angularjs-components


    【解决方案1】:

    您可以使用templateUrl 的函数来构造URL。但是,与指令不同的是,组件templateUrl 函数是可注入(参考docs),这意味着您可以将常量(或任何其他可注入服务)注入其中。正是您需要的:

    .component('row', {
      bindings: {
        details: '@',
        zip: '@'
      },
      controller: 'RowController',
      templateUrl: function(basePath, $rootScope) { // $rootScope is an example here
        return basePath + 'modules/row.html'
      }
    })
    

    还支持缩小安全数组表示法:

    templateUrl: ['basePath', '$rootScope', function(basePath, $rootScope) {
      return basePath + 'modules/row.html'
    }]
    

    演示: http://plnkr.co/edit/jAIqkzZGnaEVPaUjyBrJ?p=preview

    【讨论】:

    • 完美!我没有想到将 templateUrl 变成一个函数。
    猜你喜欢
    • 2016-09-15
    • 2018-06-10
    • 2016-04-25
    • 2016-12-21
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多