Question

How can I include a template URL inside link function in a directive? I am trying to do something like this:

app.directive('something', function($compile,$timeout) {

   return: {

      link: function(scope,element,attrs) {

           var htmlText = ???? // HOW TO INCLUDE A TEMPLATE URL HERE??

            $compile(htmlText)(scope, function(_element,_scope) {
         element.replaceWith(_element);                 
    });

      }, 

   }

}); 

When I searched, I understand that Angular directives can use templateUrl. But I am trying to store the html codes to a variable that is placed inside the link which in the end gets compiled. Usually for small codes, I just type the HTML inline to var htmlText. But if I have a lot of code, I want to save that to a separate html file and then call that for that variable (like its shown in example above). So my questions are

1) How can I add a link to template URL for a variable inside link?

2) When I am adding the url path, do I add the relative path from where the index.html file is located or the path from where that directive file is located?

Was it helpful?

Solution

Well, for a workaround you could just use ng-include in a normal <div> that you render with $compile, so something like:

link: function(scope,element,attrs) {

       var htmlText = '<div ng-include="path/to/template.html"></div>';

       $compile(htmlText)(scope, function(_element,_scope) {
       element.replaceWith(_element);                 
});

[EDIT]

There is even a nicer solution in this Thread. The Path depends on how your Webserver is configured. But usually yes, its the relative Path of your Index.html.

OTHER TIPS

You can use $templateCache.

Here is the code, that shows how it works:

<body ng-app="App">
    <!-- Include template in $templateCache AUTOMATICALLY -->
    <script type="text/ng-template" id="auto.tpl.html">
        <span style="background-color:yellow">{{title}}</span>        
    </script>

    <dir tpl-id="auto.tpl.html" title="Automatic"></dir>
    <dir tpl-id="manual.tpl.html" title="Manual"></dir>
</body>

script:

angular.module('App',[])
.directive('dir',['$templateCache','$compile',function($templateCache,$compile){
    return {
        restrict:'E',
        scope:true,
        link:function($scope, iElement, attrs){
            //Include template in $templateCache MANUALLY
            $templateCache.put('manual.tpl.html','<span style="background-color:red">{{title}}</span>');
            //----------------------------            

            $scope.title = attrs['title'];
            $compile($templateCache.get(attrs['tplId']))($scope,function(cElement){
                iElement.replaceWith(cElement);                
            });
        }
    };
}]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top