JPNN
JPNN

Reputation: 403

Dynamic generated Custom Directive Not loaded correctly when using TemplateUrl

Custom Directive that is using TemplateUrl is not evaluating correctly the angular expression whenever I try to load the directive dynamically (e.g.: using Jquery and $compile) as below :

var  scope = angular.element(document.getElementById("test1")).scope();
var _html='<div>{{name}}-</div><mydirectivewithtemplateurl Generated Dynamically Using TemplateUrl >Not Succeed</mydirectivewithtemplateurl>';
$('#content').html($compile(_html)(scope));

But:

1- When I put directly the same directive (using TemplateUrl) into the page as below :

<mydirectivewithtemplateurl waytoload="Generated Stastically Using TemplateUrl ">Not Succeed</mydirectivewithtemplateurl>

It is working fine.

2- Also works fine when I use Template instead of TemplateUrl and loaded dynamically the same way as above:

 var  scope = angular.element(document.getElementById("test1")).scope();
            var _html='<div>{{name}}-</div><mydirectivewithtemplateonly  waytoload="Generated Dynamically Using Template" >Not Succeed</mydirectivewithtemplateonly>';
           $('#content').html($compile(_html)(scope));
           setTimeout(function(){ scope.$apply();});

here is the custom directive I am using TemplateUrl

app.directive('mydirectivewithtemplateurl',function ()
    {

      return {
     scope : {
       loadedstate:'@waytoload',

     },
    //template:'<div>{{loadedstate}}</div>',
     templateUrl:'grid.html',

    }
    })

and here is the custom directive that I am using Template :

app.directive('mydirectivewithtemplateonly',function ()
{

  return {
  scope : {
   loadedstate:'@waytoload',

 },
template:'<div class="panel panel-primary">{{loadedstate}}</div>'
// templateUrl:'grid.html',

} })

So my question is : how to solve evaluating angular expression correctly inside the custom Directive when I use TemplateUrl (instead of Template ) and load it dynamically (jquery and @compile) for better understanding about my problem please see the full demo with the code : http://plnkr.co/edit/f2eUdUwQF7o4pMCOHkLw?p=preview and feel free to update directly the code . Please Note : defined Path in TemplateUrl is correct and is tested when added directly to that page Thanks

Upvotes: 0

Views: 584

Answers (2)

Jason
Jason

Reputation: 349

Something todo with async loading that template, timing could be an issue, so use a promise, try putting the call to the template in a link function and comment out templateURL :

link : function(){
   $templateRequest("grid.html").then(function(html){
      var template = angular.element(html);
      element.append(template);
      $compile(template)(scope);
   });
 }

Upvotes: 0

rrd
rrd

Reputation: 5957

You could try an absolute path:

...
templateUrl: 'app/directives/mydirective.html'
...

Upvotes: 0

Related Questions