NG筆記17-範本(Template)
1 |
範本(Template)是MVVM的基本功能之一,與KO相比,NG的範本功能多了將範本存在外部HTML檔的彈性。開始前,先回味本次復刻對象: KO範例13 - Template範本功能。
先前介紹過的ng-repeat Directive已內含範本概念,例如:
<tr ng-repeat="user in model.users" ng-class="user.addFlag ? 'new' : ''"
anim-hide="user.removeFlag" anim-hide-done="model.removeUser()">
<td><span>{{ user.id }}</span>
</td>
<td><span>{{ user.name }}</span>
</td>
<td><span style='text-align: right'>{{ user.score }}</span>
</td>
<td><a ng-click="model.markUserRemoved(user)" class="btn">移除</a>
</td>
</tr>
在<tr>與</tr>間以HTML穿插ng-* Directive或{{ prop }}方式定義呈現樣式,即相當於內嵌範本。而NG提供了ng-include可將範本提取成獨立片段加以共用。例如:
<script type="text/ng-template" id="/contactTmpl.html">
<dl>
<dt>Name</dt><dd>{{ member.name }}</dd>
<dt>Phone</dt><dd>{{ member.phone }}</dd>
</dl>
</script>
</head>
<body ng-controller="defaultCtrl">
<h3>Leader</h3>
<div class='memb-list'>
<span ng-repeat="member in [model.leader]">
<span ng-include src="'/contactTmpl.html'"
ng-show="member" class='cont-block'>
</span>
</span>
</div>
<br />
<h3>Members</h3>
<div class='memb-list'>
<span class='cont-block' ng-repeat="member in model.members"
ng-include src="'/contactTmpl.html'">
</span>
</div>
以上範例,範本內容被寫進<script type="text/ng-template" id="/contactTmpl.html">放在<head>區段,而底下的兩處ng-repeat透過<span ng-include src="'/contactTmpl.html'">指定由其決定連絡人呈現樣式,達到共用。Live Demo
範本src="'/contactTmpl.html'"有一些提示:1) 設定值被寫成'/…'字串常數,代表可用ViewModel屬性動態指定 2) id名稱刻意取成contactTmpl.html,暗示範本也能獨立存成HTML檔案。
來看以下的例子:
在這個範例中,我們另外建立兩個HTML檔:
lab13at1.html (不需要<html>、<head>、<body>,只要寫入範本片段就好)
<dl>
<dt>Name</dt><dd>{{ member.name }}</dd>
<dt>Phone</dt><dd>{{ member.phone }}</dd>
</dl>
lab13at2.html
<dl>
<dt>姓名</dt><dd>{{ member.name }}</dd>
<dt>電話</dt><dd>{{ member.phone }}</dd>
</dl>
主程式新増範本下拉選單,由model.tmpls = ["lab13t1.html","lab13t2.html"]取得選項,並繫結到selTmple屬性。引用範本時寫成<span ng-include="model.selTmpl">,使用範本將由下拉選單控制,由XHR取回範本內容套用,每次切換後也會立即反應。
<select ng-model="model.selTmpl"
ng-options="data for data in model.tmpls">
</select>
<h3>Leader</h3>
<div class='memb-list'>
<span ng-repeat="member in [model.leader]">
<span ng-include="model.selTmpl"
class='cont-block show-anim'>
</span>
</span>
</div>
<br />
<h3>Members</h3>
<div class='memb-list'>
<span class='cont-block' ng-repeat="member in model.members"
ng-include="model.selTmpl">
</span>
</div>
[NG系列]
Comments
# by Phoenix
ko也是有機會做到存取外部html的特性的,只要做出一個TemplateEngine就行了。 var koEngine = <KnockoutTemplateEngine>new ko.nativeTemplateEngine(); koEngine.makeTemplateSource = function (template: { Category: string; TemplateName: string; }) { return new ko.templateSources.DynamicFormTemplateSource(...); } ko.setTemplateEngine(koEngine);