如何在AngularJS中点击后将HTML模板附加到div /指令?

3

i have this situation:

<somebutton></somebutton>

...

app.directive("somebutton", function(){
    return {
        restrict: "E",

        scope: {
          // not sure what i can do here
        },

        template: '<button ng-click="loadTemplate()" type="button">Text</button>',

        link: function(scope, element){
            scope.loadTemplate = function(){

                //TODO: append "home.html" template inside body directive
            }
        }
    }
});

...

<script type="text/ng-template" id="home.html">
    <div>home</div>
</script>

...

<div body ></div>

另一种做法是在HTML中添加按钮而不是模板。

<button ng-click="loadTemplate()" type="button">Text</button>

然后可能有一个控制器,具有loadTemplate()方法来加载模板。

但我不确定如何实现。

感到困惑吗?是的 :)

对这个问题有什么想法吗?

谢谢


我最近开始学习Angular,但是对于正确的操作方式感到困惑...例如,Angular HTML被视为模板,因此不确定是否可以使用其他模板工具与Angular一起使用...期待得到一些答案... - Anil Namde
1个回答

8
请看 ngInclude,如果适用的话。你可以将它绑定到一个模板URL上,以动态更改已加载的模板。
请查看文档中的示例以及这个简单的plnkr
<body>
  <button ng-click="template='home.html'">Home</button>
  <button ng-click="template='home2.html'">Home 2</button>
  <div ng-include src="template"></div>
</body>
<script type="text/ng-template" id="home.html">
    <div>loaded home</div>
</script>
  <script type="text/ng-template" id="home2.html">
    <div>loaded home 2</div>
</script>

同时注意,大多数AngularJS应用程序可能正在使用内置路由来根据url加载适当的控制器和视图。有关更多信息,请参见教程$route的文档/示例。


2
这将切换模板。我想要加载/追加一个模板到一个div/directive中。 我的问题可能会让人有点困惑。 - Patrioticcow
在这种情况下,也许$compile文档会有所帮助。 - Gloopy
对我来说什么都没有发生。 - deFreitas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接