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).

Community
  • 1
  • 1
Daniel Robinson
  • 13,806
  • 18
  • 64
  • 112

2 Answers2

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="angular.js@1.3.x" 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!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
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>"
    };
}]);
jlowcs
  • 1,933
  • 1
  • 10
  • 16
  • 1
    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... – jlowcs Mar 12 '15 at 21:05