13

I've been trying to use the new Angular 1.5 component syntax in a project, but I can't figure out how to inject a dependency into the component definition.

Here's my attempt at refactoring an existing directive to a component:

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

For various reasons, we inject the constant basePath into all of our directives as part of the templateUrl.

How do I do this on a component, since the component definition is not a function?

1 Answer 1

14

You can use a function for templateUrl to construct URL. However, unlike the one for directives, component templateUrl function is injectable (ref docs), which means that you can inject constant (or any other injectable service) into it. Exactly what you need:

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

Minification-safe array notation is also supported:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! It didn't occur to me to make templateUrl into a function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.