Angularjs 如何从指令中插入分部?

Angularjs 如何从指令中插入分部?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我有一个如下的自定义指令。在其中,我想插入部分文档中的html: .directive('myDirective', function($parse){ return { restrict: 'A', scope: { foo: '=' }, link: function(scope, element, attrs){ //add children to element[0] using html from partials/content.html //.

我有一个如下的自定义指令。在其中,我想插入部分文档中的html:

.directive('myDirective', function($parse){ 
return { 
  restrict: 'A', 
  scope: { foo: '=' }, 
  link: function(scope, element, attrs){ 
    //add children to element[0] using html from partials/content.html
    //...
  }
});

Google/Stack没有透露太多信息,有没有办法做到这一点,或者我不打算用这种方式使用指令?

你可以做三件事

  • 您可以将
    $templateRequest
    设置为html页面,该页面在内部生成一个ajax来获取html,然后将该html放入
    $templateCache
  • 代码

    $templateRequest('mypath.html').then(function(res){
       //inside you could have html content in res.data;
       var html = res.data;
    })
    
    app.run(function($templateCache){
        $templateCache.put('mytemplate.html', '<div>My HTML</div>')
    })
    
    //inside directive do below thing
    var html = $templateCache.get('mytemplate.html');
    
  • 您可以将
    html
    内容放入运行块中的
    $templateCache
    服务中,然后在需要时使用
    $templateCache.get('templateName')
  • 代码

    $templateRequest('mypath.html').then(function(res){
       //inside you could have html content in res.data;
       var html = res.data;
    })
    
    app.run(function($templateCache){
        $templateCache.put('mytemplate.html', '<div>My HTML</div>')
    })
    
    //inside directive do below thing
    var html = $templateCache.get('mytemplate.html');
    

    为什么不直接使用
    ng include
    ?另外,还有一个比-$http更简单的选项,使用
    $templatereRequest
    自动进行缓存。@NewDev
    ng include
    ,这将生成一个子作用域,该子作用域将被原型继承自指令。。这没有意义吗?我同意
    $templatereRequest
    的内容。是否会更新我的答案您所说的
    ng include
    ?这是真的(子范围没有固有的缺点),但与问题有点正交。你自己在自己的回答中回避了这个问题,没有显示你要链接的范围谢谢@PankajParkar,发现这也帮助了我:
    templateUrl:'somePartial.html',
    而不是
    链接:
    不做你想做的事吗?