Manohar
Manohar

Reputation: 1185

Add external html template in angularjs

I am using a directive to inject some specific content on my page. We have a requirement when the url attribute points to an html file and the contents of that file need to be rendered on my page. How can I do that

<section>
<block-with-html 
url = "locatiion of html file">
</block-with-html>
</section>

angular
.module('app.blockWithHtml', [])
.directive('blockWithHtml', BlockWithHtmlDirective);

 function BlockWithHtmlDirective(ConfigBlocksService) {
   return {
     restrict: 'E',
     scope: {
       url: '='
     },
     template: `
       <section  >
         <h4>block with html</h4>
         <div>content form the html file goes here</div>
       </section>
     `,
   }
 }

Upvotes: 0

Views: 320

Answers (1)

Rotem jackoby
Rotem jackoby

Reputation: 22088

  1. If you want to pass fields which are not expressions, try this:

       <section>
           <block-with-html 
              type='image'
              url = "locataion of html file">
              </block-with-html>
        </section>
    
        angular
        .module('app.blockWithHtml', [])
        .directive('blockWithHtml', BlockWithHtmlDirective);
    
         function BlockWithHtmlDirective(ConfigBlocksService) {
    
        return {
            restrict: 'E',
            template: function(tElement,tAttr){
               //Use the tAttr.url 
              var imageTemplate   = '<img src="tAttr.url">';
              var dynamicTemplate = '<ng-include src=”getTemplateUrl(tAttr.url)”/>';
    
            return tAttr.type == 'image' ? imageTemplate : dynamicTemplate;
            }
            controller: function($scope) {
               $scope.getTemplateUrl = function(url) {
               //Some logic here..
            }
        }
        };
    
  2. If you asking that the source template of the directive will be set "on the fly" according to a passed expression - it is not possible. The reason is that the template of the directive is being set on the compilation phase - this is where angularjs is 'opening' the template of all the directives and putting them on dom but the scope is not being created yet , this will happen in the link phase where angularjs goes over each directive's template and create a scope for it and bind all the events. For summary, you can't pass a template location based on an expression.

Upvotes: 1

Related Questions