Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular component relative templateUrl

I'm developing a modular angular application with I defined I folder path (constant : BASE_PATH : "path/to/folder") in angular-module-1 module. I want to re-used this constant in a angular component located in another module (angular-module-2)of my application. I want to use this constant many time in my project.

module.component("relationshipSearch", {
templateUrl: BASE_PATH +'/link/to/other/folder',

witch is the best way to define this constant as a global variable visible in all the solution project Here is my project structure:

project
|-- angular-module-1
|   |-- angular-module-1.js
|   |-- angular-module-1.html
|-- angular-module-2
|   |-- angular-module-2.js
|   |-- angular-module-2.html
like image 566
Saad Avatar asked Feb 15 '26 06:02

Saad


2 Answers

I'd say that create a common module named as angular-common where you can place common stuff like common service, factory, directive, constants, etc.

Then add the constant inside angular-common(this would be completely independent and plug-able) module. like below

//assuming `angular-common` is already defined
angular.module('angular-common').constant('commmonSetting', {
  'BASE_PATH': '/link/to/other/folder'
})

Next, inject this common module in app(which is main module, going to be used in ng-app/bootstrap) like below

angular.module('app', ['angular-common', 'ngRoute', ...other dependencies..])

When you wanted to use BASE_PATH just inject commmonSetting dependency in controller/component wherever you want.

app.component('myComponent', {
  templateUrl: function(commmonSetting){
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
})
like image 192
Pankaj Parkar Avatar answered Feb 16 '26 21:02

Pankaj Parkar


Sorry, for posting on an old thread with an accepted answer, but I wanted to say that the accepted answer is not minification safe. The minification safe way to write this is:

app.component('myComponent', {
  templateUrl: function($injector){
    var commmonSetting = $injector.get('namespace.CommmonSetting');
    return commmonSetting.BASE_PATH +'/link/to/other/folder';
  },
  ....
});
like image 20
GamerDev Avatar answered Feb 16 '26 21:02

GamerDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!