javascript 如何使用angular js在单击时将html模板附加到div /指令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15402772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:39:51  来源:igfitidea点击:

how to append a html template to a div/directive on click with angular js?

javascripthtmltemplatesbuttonangularjs

提问by Patrioticcow

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>

Other way of doing this could be to have the button in html instead of an template

这样做的其他方法可能是在 html 中使用按钮而不是模板

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

then maybe have a controller that has the loadTemplate()method that loads the template

那么也许有一个控制器,它具有loadTemplate()加载模板的方法

but im not sure how this can be done.

但我不确定如何做到这一点。

Confusing? yes :)

令人困惑?是的 :)

Any ideas on this issue?

关于这个问题的任何想法?

thanks

谢谢

回答by Gloopy

Take a look at ngIncludein case it fits your needs. You can bind it to a template url to dynamically change the loaded template.

看看ngInclude它是否符合您的需求。您可以将其绑定到模板 url 以动态更改加载的模板。

Check out the documentationfor an example as well as this simple plnkr.

查看文档以获取示例以及这个简单的 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>

Also notethat most AngularJS apps are likely using the built in routing to load appropriate controllers and views based on the url. See the tutorialand documentation/example on $routefor more information.

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