Angular 1.5 组件依赖注入

Angular 1.5 component dependency injection

我一直在尝试在项目中使用新的 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 的一部分注入到我们所有的指令中。

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

您可以使用 templateUrl 的函数构造 URL。但是,与指令不同的是,组件 templateUrl 函数是 injectable (ref 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