使用TemplateUrl时未正确加载动态生成的自定义指令



每当我尝试动态加载指令(例如:使用Jquery和$compile)时,使用TemplateUrl的自定义指令没有正确评估角度表达式,如下所示:

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

但是:

1-当我直接将相同的指令(使用TemplateUrl)放入页面时,如下所示:

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

它运行良好。

2-当我使用Template而不是TemplateUrl并以与上面相同的方式动态加载时,也可以很好地工作:

 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();});

这是我使用的TemplateUrl 的自定义指令

app.directive('mydirectivewithtemplateurl',function ()
    {
      return {
     scope : {
       loadedstate:'@waytoload',
     },
    //template:'<div>{{loadedstate}}</div>',
     templateUrl:'grid.html',
    }
    })

这是我使用的自定义指令模板:

app.directive('mydirectivewithtemplateonly',function ()
{
  return {
  scope : {
   loadedstate:'@waytoload',
 },
template:'<div class="panel panel-primary">{{loadedstate}}</div>'
// templateUrl:'grid.html',
} })

因此,我的问题是:当我使用TemplateUrl(而不是Template)并动态加载(jquery和@compile)时,如何解决在自定义指令中正确评估角度表达式的问题。为了更好地了解我的问题,请参阅代码的完整演示:http://plnkr.co/edit/f2eUdUwQF7o4pMCOHkLw?p=preview并且可以直接更新代码。请注意:TemplateUrl中定义的路径是正确的,并且在直接添加到该页面时进行了测试感谢

异步加载该模板时,时间可能会有问题,所以使用promise,尝试将对模板的调用放在链接函数中,并注释掉templateURL:

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

您可以尝试一个绝对路径:

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

最新更新