Search code examples
javascriptangularjsangularjs-ng-include

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


Solution

  • 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!