如何使用AngularJS中的自定义指令将一个html页面插入另一个html页面?

时间:2014-11-04 09:21:14

标签: javascript html angularjs

使用自定义指令,我想将一个HTML页面添加到另一个,这怎么办? 自定义指令如下:

(this is the .js file)
 fbModule.directive('fbLogin', function(){
        return {
            template : html
        }        
 })

要包含的html页面是:

(this is the .html file to be included)
<div ng-controller="fbCtrl">
    <button ng-click="doFacebookLogin">
        <img src="modules/shippingAddress/fastfill_fb.png" width="140px" height="25px;" style="margin-right: 8px; cursor:pointer">
    </button>
</div>

上面代码应该出现的页面是:

(this is the .html file in which the above html should come)
<div fbLogin></div>
<div style="font-size: x-small; color: black;">Save on typing. Use your FB data.</div>

请帮忙.. 提前致谢

5 个答案:

答案 0 :(得分:1)

您应该使用ngInclude将HTML注入另一个页面 https://docs.angularjs.org/api/ng/directive/ngInclude

<ng-include src="somehtmlfile.html"></ng-include>

答案 1 :(得分:1)

如果您需要获取如下所示的外部html,则需要将模板更改为 templateUrl

  

templateUrl 也可以是返回HTML网址的函数   要加载并用于指令的模板。 Angular会打电话   templateUrl函数有两个参数:元素即   调用了一个指令,并且一个与之关联的attr对象   元件。

Working Demo

  fbModule.directive('fbLogin', function() {
    return {
      template: 'template.html'
    };
  });

  fbModule.directive('fbLogin', function() {
    return {
      templateUrl: 'template.html'
    };
  });

答案 2 :(得分:0)

基本上:

 fbModule.directive('fbLogin', function(){
         return {
             templateUrl : "...path to html"
         }});

...但请阅读开发人员指南https://docs.angularjs.org/guide/directive

答案 3 :(得分:0)

使用templateUrl而不是模板。你的templateUrl必须指向目录中的html文件。 在这里,我的templeUrl指向my.html,它位于模板目录中。

fbModule.directive('fbLogin', function(){
        return {
            templateUrl : "/templates/my.html"
        }        
 })

答案 4 :(得分:0)

如果你想用指令加载的html文件完全替换指令标签,你应该使用templateUrl: 'path/to/file.html'replace: true,这样你的指令标签就会被html取代而不是被包含在其中。 这是指令示例:

app.directive('fbLogin', function(){
  return {
      templateUrl : 'include.html',
      replace: true
  }        
});

此外,这是工作plunker