我们说我有以下标记:
<main ng-controller="MainController">
<article id="story-container"></article>
<button ng-click="newSection()">+ Add Section</button>
</main>
我需要在按钮点击时编译并在article元素中附加以下模板。
<script id="newSectionTmpl" type="text/ng-template">
<section>Hello, {{name}}!</section>
</script>
我尝试过这样的事情,但不确定这是否是一个好方法:
app = angular.module('myApp', []);
app
.controller('MainController',['$scope', '$compile', function($scope, $compile) {
$scope.name = "Denis";
$scope.newSection = function() {
var tmpl = $('#newSectionTmpl').html();
var $el = $('#story-container');
console.log(tmpl);
var html = $compile(tmpl)($scope);
$el.append(tmpl);
}
}
]);
另外,如何从外部文件加载我的模板? 以下是jsBin的链接:http://jsbin.com/zuyicewexahi/5/edit?html,js,output
答案 0 :(得分:0)
尝试 ng-include 指令 ng-include documentation
<div class="modal-header">
<form ng-include src="'/src/sample.html'"></form>
</div>
sample.html是一个外部文件,它将使用ng-include指令
加载到当前的html中答案 1 :(得分:0)
Angular太棒了,你不需要那里的大部分jquery。见下面的plunkr: http://plnkr.co/edit/yqhnQyR4NrFvnUBn7ite?p=preview
您需要将姓名设置为&#39; Noypi&#39; ......开玩笑......&#39;
app.controller('MainController',['$scope', function($scope) {
$scope.name = "Noypi";
$scope.content = "";
}]);
HTML ...
<div ng-controller="MainController">
<button ng-click="content = 'newSectionTmpl'">+ Add Section</button>
<div ng-include src="content"></div>
</div>