我刚刚开始使用 angularJS 并努力为我正在尝试做的事情找出合适的架构。我有一个单页应用程序,但URL 应始终保持不变;我不希望用户能够导航到根之外的任何路由。在我的应用程序中,有一个主要的 div 需要承载不同的 View 。当访问新 View 时,我希望它接管主 div 中的显示。以这种方式加载的 View 可能会被丢弃或隐藏在 DOM 中 - 我很想知道每种 View 如何工作。
我想出了一个粗略的工作示例来说明我正在尝试做的事情。 See working example here in this Plunk.基本上,我想将 HTML 动态加载到 DOM 中,并让标准的 angularJS Controller 能够连接到新的 HTML 中。有没有比使用我在这里的自定义指令并使用 $compile() 连接到 Angular 更好/更简单的方法?也许有某种类似路由器的东西,但不需要 URL 发生变化就可以运行?
这是我目前使用的特殊指令(取自另一篇 SO 帖子):
// 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。模板可以轻松地存在于远程 URL 中。
这是一个工作演示: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>
关于javascript - AngularJS 如何动态添加 HTML 并绑定(bind)到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19845950/