13

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

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

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

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

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

4

1 回答 1

14

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

.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

于 2016-05-14T18:54:39.190 回答