如何将一个HTML模板添加到点击具有角的js的div /指令? [英] how to append a html template to a div/directive on click with angular js?
问题描述
我有这种情况:
<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而不是一个模板按钮
Other way of doing this could be to have the button in html instead of an template
<button ng-click="loadTemplate()" type="button">Text</button>
那么也许有一个具有加载模板 loadTemplate()
方法的控制器
但林不知道如何可以做到这一点。
but im not sure how this can be done.
混淆?是的:)
在这个问题上任何想法?
Any ideas on this issue?
感谢
推荐答案
采取案例来看看 ngInclude
它适合你的需求。你可以把它绑定到一个模板URL动态地更改装载模板。
Take a look at ngInclude
in case it fits your needs. You can bind it to a template url to dynamically change the loaded template.
查看文档一个例子以及本的simple plnkr 。
Check out the documentation for an example as well as this simple 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应用程序有可能使用内置的路由负载根据网址适当的控制器和视图。请参见教程和文档/例子上的了解更多信息$航线。
Also note that most AngularJS apps are likely using the built in routing to load appropriate controllers and views based on the url. See the tutorial and documentation/example on $route for more information.
这篇关于如何将一个HTML模板添加到点击具有角的js的div /指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!