0

I am trying to extend the ng-include directive with this:

module.directive('incComp', [function () {
    return {
        template: "<div ng-include=\"'app/component/{{incComp}}/template.html'\"></div>"
    };
}]);

and I use it like this:

    <div inc-comp="counter"></div>

but the get request that goes out is for:

/app/component/%7B%7BincComp%7D%7D/template.html

I'm not sure how to get it insert the value of the inc-comp attribute rather than just using the literal value in the template string. I got the notion of doing this from this SO question (2nd answer).

2 Answers 2

4

The task can also be done without ng-include and without isolated-scope, a good solution i think:

plnk demo here

index.html

  <div ng-app="app" ng-controller="appCtrl">
    <div add-template type="lion"></div>
    <div add-template type="fox"></div>
  </div>
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.14/angular.js" data-semver="1.3.14"></script>
  <script type="text/javascript">
    var app = angular.module("app", []); 
    app.directive('addTemplate', function() {
      return {
        templateUrl: function(elem, attr) {
          return 'template_' + attr.type + '.html';
        }
      }
    });
  </script>

template_fox.html

<div> This is Fox Template </div>

template_lion.html

<div> This is Lion Template </div>

Happy Helping!

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

1 Comment

I forgot you could do that.
3

incComp is evaluated to nothing in your template. You need to add it to your scope. And ng-include takes an expression, not a template. Something like this should work better:

module.directive('incComp', [function () {
    return {
        scope: true,
        controller: function($scope, $element, $attrs) {
            $scope.tpl = 'app/component/' + $attrs.incComp + '/template.html'
        },
        template: "<div ng-include=\"tpl\"></div>"
    };
}]);

You could also do that in the link function instead of the controller.

I didn't test it though...

EDIT: I suppose you could also do something like this:

module.directive('incComp', [function () {
    return {
        scope: {
            incComp: '@'
        },
        template: "<div ng-include=\"'app/component/' + incComp + '/template.html'\"></div>"
    };
}]);

1 Comment

Those 2 ways end up with the same result, but they have different pros and cons. One creates a controller, the other one creates an isolate scope...

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.