4

is it possible to create a AngularJS Component with a dynamic templateUrl? Means I want to inject a service into the Component that gives me a base path to the template:

i.e.: templateUrl: configuration.baseScriptPath + '...html'

It is possible with a Directive, but how to do this with a Component?

angular.module('runtime')
    .component('textInput', {

        templateUrl: /*configuration.baseScriptPath + */'fd/components/text_input_instance.html',
        controller: [
            '$scope', '$element', 'focusInputGroup', 'configuration',
            function ($scope, $element, focusInputGroup, configuration) {
4
  • If it is working in directive, it should work in Component as well because 'templateUrl' property is not modified.. Commented Jun 22, 2016 at 10:33
  • I want to inject configuration so that it is useable in templateUrl. Commented Jun 22, 2016 at 10:37
  • Could you share your component code? Commented Jun 22, 2016 at 10:44
  • Just added. The comment shows what I want to accomplish, but how can configuration be injected? Commented Jun 22, 2016 at 10:49

2 Answers 2

9

Instead of templateUrl you can use template and ng-include, like this:

angular.module('runtime')
    .component('textInput', {

        template: '<div ng-include="getTemplate()">',
        controller: [
            '$scope', '$element', 'focusInputGroup', 'configuration',
            function ($scope, $element, focusInputGroup, configuration) {

           $scope.getTemplate = function () {
               return configuration.baseScriptPath + 'fd/components/text_input_instance.html';
          };
Sign up to request clarification or add additional context in comments.

Comments

7

templateUrl property of component also takes a function. so you can try this,

angular.module('runtime')
  .component('textInput', {

      templateUrl: ['$configuration', function($configuration) {
        return $configuration.basepath + '.html'
      }],
      controller: [
          '$scope', '$element', 'focusInputGroup', 'configuration',
          function($scope, $element, focusInputGroup, configuration) {

2 Comments

Should be templateUrl: [...], otherwise it will just print the HTML template file name as template is a string.
correct. i am used to use <component-name></component-name> .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.