Daniel Robinson
Daniel Robinson

Reputation: 14898

How to extend Angularjs ng-include directive?

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

Upvotes: 0

Views: 845

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

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!

Upvotes: 4

jlowcs
jlowcs

Reputation: 1933

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>"
    };
}]);

Upvotes: 3

Related Questions