2014-09-04 68 views
1

比方說,我有以下標記:如何在按鈕單擊時渲染外部模板?

<main ng-controller="MainController"> 
    <article id="story-container"></article> 
    <button ng-click="newSection()">+ Add Section</button> 
</main> 

我需要編譯和追加文章元素中下面的模板上的按鈕點擊。

<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

要加載模板外部文件,使用jquery的load()函數。這是加載外部文件非常有用的功能。欲瞭解更多信息,請查看此鏈接:http://api.jquery.com/load/ – 2014-09-04 04:35:45

+0

謝謝!我想知道是否有角度的做法... – 2014-09-04 04:46:02

+0

使用$ templateCache而不是jQuery。 – 2014-09-04 06:46:42

回答

0

嘗試NG-包括指令 ng-include documentation

<div class="modal-header"> 
<form ng-include src="'/src/sample.html'"></form> 
</div> 

sample.html是一個外部文件,該文件將使用加載到您當前的HTML NG-include指令

+0

嗨,Jan!它將在編譯階段渲染sample.html。如何在按鈕單擊時渲染sample.html並將其附加到特定元素? – 2014-09-04 05:11:35

0

Angular很棒,你不需要大部分的jquery。見下面plunkr: http://plnkr.co/edit/yqhnQyR4NrFvnUBn7ite?p=preview

您需要設置名稱 'Noypi' ... '只是在開玩笑......'

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> 
+0

好主意!但它只會追加模板一次。如果我想要n個模板來渲染呢? – 2014-09-04 19:37:33

+0

這是另一個問題。接受這個答案,爲新問題創建一個plunkr,我會告訴你如何。 – 2014-09-05 04:27:46