Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 component dependency injection

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?

like image 794
epb Avatar asked May 14 '16 18:05

epb


People also ask

Which components can be injected as dependency in AngularJS?

The "Application Module" can be injected as a dependency in AngularJS.

Which components Cannot be injected as a dependency in AngularJS?

Note that you cannot inject "providers" into run blocks. The config method accepts a function, which can be injected with "providers" and "constants" as dependencies. Note that you cannot inject "services" or "values" into configuration. The provider method can only be injected with other "providers".

Does Angular use dependency injection?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

What is $inject in AngularJS?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.


1 Answers

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

like image 189
dfsq Avatar answered Oct 20 '22 10:10

dfsq