How to use defined text/ng-template in AngularJS directive How to use defined text/ng-template in AngularJS directive angularjs angularjs

How to use defined text/ng-template in AngularJS directive


HTML

<script type="text/ng-template" id="myDirectivesCustomTemplate.html">    <ul>        <li ng-repeat="value in values">        <a ng-click="doSomething({id:value.id})">                            {{value.name}}        </a>        </li>    </ul></script><div ng-controller="MainCtrl">     <div my-directive template="myDirectivesCustomTemplate.html" mydata="mydata" mycallback="doSomething(id)"></div></div>

JS

app.controller('MainCtrl',function($scope){    $scope.mydata = [{id:1,name:'One'},{id:2,name:'Two'},{id:3,name:'Three'}];    $scope.doSomething = function(id){        alert(id);     }});app.directive('myDirective', function($templateCache,$compile) {    return {        restrict: 'A',        scope:{            template : "@",            mydata : "=",            mycallback:"&"        },        link: function(scope,element) {            var template = $templateCache.get(scope.template);            scope.values = scope.mydata;            scope.doSomething = scope.mycallback;            element.append($compile(template)(scope));        }    }});


Looking at your directive i can suggest try ng-include. Where you want to do

//$compile(ComboboxDropdownTemplate) +    '</div>'

change it to

<span ng-include='templateUrlPropertyOnScope'>'</div>'

templateUrlPropertyOnScope property should point to a template either on server side or in script section created with type=text/ng-template.


I know this is 4 years later but if anyone still has this question, perhaps this answer may also be found useful.

With a simple directive such as this:

<my-directive template="custom-template.html"></my-directive>

You can then refer to the template attribute in your directive, like this:

(function() {  angular    .module('app')    .directive('myDirective', myDirective);  function myDirective() {    return {      restrict: 'E',      templateUrl: function(elem, attrs) {        return attrs.template;      }    }  }}