AngularJS如何动态地添加HTML和绑定到控制器 [英] AngularJS How to dynamically add HTML and bind to controller
问题描述
我刚开始接触angularJS和努力找出正确的架构,我想要做的。我有一个单页的应用程序,但的URL应该始终保持不变;我不希望用户能够浏览到超出任何root权限的路线。在我的应用程序,也将需要主机不同的观点一个主分区。当一个新的视图被访问时,我希望它接管主分区显示。以这种方式加载视图可以扔掉的或者留下来作为隐藏在DOM - 我很感兴趣,查看各个可能的工作。
I'm just getting started with angularJS and struggling to figure out proper architecture for what I'm trying to do. I have a single page app but the URL always should stay the same; I don't want the user to be able to navigate to any routes beyond the root. In my app, there is one main div that will need to host different views. When a new view is accessed, I want it to take over the display in the main div. Views loaded in this way can be throw-away or stick around as hidden in the DOM - I'm interested in seeing how each might work.
我已经拿出了什么,我试图做一个粗略的工作示例。 请参阅本普拉克在这里工作的例子。基本上我想动态加载到HTML DOM和有标准angularJS控制器可以挂接到新的HTML。有没有更好/更简单的方法,这样做比使用自定义指令,我这里使用$编译()挂钩到角?也许有什么东西有点像路由器,但不要求网址有变化操作?
I've come up with a rough working example of what I'm trying to do. See working example here in this Plunk. Basically I want to dynamically load HTML into the DOM and have standard angularJS controllers be able to hook into that new HTML. Is there a better/simpler way to do this than by using the custom directive I have here and using $compile() to hook up to angular? Perhaps there's something sort of like the router, but doesn't require URL has changes to operate?
下面是特殊的指令,我使用至今(从另一个SO后服用):
Here's the special directive I'm using so far (taken from another SO post):
// Stolen from: http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database
myApp.directive('dynamic', function ($compile) {
return {
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
if (!html) {
return;
}
ele.html((typeof(html) === 'string') ? html : html.data);
$compile(ele.contents())(scope);
});
}
};
});
谢谢,
刘德华
推荐答案
我会使用内置的 ngInclude
指令。在下面的例子中,你甚至都不需要编写任何JavaScript。模板可以很容易地住在一个偏远的网址。
I would use the built-in ngInclude
directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.
下面是一个工作演示: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E? p = preVIEW
Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
这篇关于AngularJS如何动态地添加HTML和绑定到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!