ng-include用法

<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">
<h3>
{{product.name}}
<em class="pull-right">{{product.price | currency}}</em>

</h3>
<section ng-controller="PanelController as panel">
.....


抽出中間兩段到 product-title.html 裡,在 h3 的 tag 中加入 ng-include="'product-title.html'",注意在雙引號中間引用 html 頁面時需要再加上單引號

<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">
<h3 ng-include="'product-title.html'">
</h3>
<section ng-controller="PanelController as panel">
.....


真正在頁面產生出來的文件會包含 angulajs 的一些語法跟 css style

<h3 ng-include="'product-title.html'" class="ng-scope">

<span class="ng-scope ng-binding">Awesome Multi-touch Keyboard</span>
<em class="pull-right ng-scope ng-binding">$250.00</em>

</h3>

 

客製化的 Directives(tag name)

來取代 ng-include

<h3 ng-include="'product-title.html'"></h3>
變成
<product-title></product-title>


由此可以知道,若是前端頁面區分的比較詳細後,HTML 裡的 Tag 都用 AngularJS Directive 的方式來撰寫,可以將頁面簡化為可讀性高的頁面,如下所示

<aside class="col-sm-3">
<book-cover></book-cover>
<h4><book-rating></book-rating></h4>

</aside>
 


<div class="col-sm-9">

<h3><book-title></book-title></h3>


 <book-authors></book-authors>


 <book-review-text></book-review-text>


 <book-genres></book-genres>

</div>


建立客製化 Directives 的方式,在 JavaScript 裡使用 app.directive('名稱', function(){...});
而這邊的名稱需要注意,寫在 HTML 裡面的名詞中間採用 - 連接時,在 js 中需要以駝峰式的方法命名

<product-title></product-title>
對應成
app.directive('productTitle', function(){
return {
restrict: 'E', // E for Element (another way, 'A' for Attribute)
templateUrl: 'product-title.html' // template 的 url
};
});


上面介紹得為 Element Directives的方法,另一種 Attribute Directives 的方式,是將 Directives 寫在 HTML Tag 中的屬性
e.g.

<h3 product-title></h3>
app.directive('productTitle', function(){

return {
restrict: 'A',

 templateUrl: 'product-title.html'
};
};


兩種寫法最後都會產生相同的 HTML 結構

<h3>
{{product.name}}
<em class="pull-right">${{product.price}}</em>
</h3>


範例:

<section ng-controller="PanelController as panel">
<ul class="nav nav-pills"> ... </ul>
<div class="panel" ng-show="panels.isSelected(1)"> ... </div>
<div class="panel" ng-show="panels.isSelected(2)"> ... </div>
<div class="panel" ng-show="panels.isSelected(3)"> ... </div>
</section>


將 section 裡的內容抽出,命名為product-panels,這時會變成

<product-panels ng-controller="PanelController as panel">
. . .
</product-panels>
與 JavaScript 內容
app.directives('productPanels', function(){
return {
restrict: 'E',
templateUrl: 'product-panels.html'
}
});


這時候需要來處理 Controller 的部分,首先將 JS 中的 Controller,搬到 app.directives 裡,然後再給一個別名
而原本 HTML 語法可以再精簡到沒有 ng-controller 在裡面

<product-panels>
. . .
</product-panels>

app.directives('productPanels', function(){
return {
restrict: 'E',
templateUrl: 'product-panels.html'
contorller: function(){ // Controller搬進來
. . .
},
controllerAs: 'panels' // 給別名
}
});
arrow
arrow
    文章標籤
    AngularJS
    全站熱搜

    soarlin 發表在 痞客邦 留言(0) 人氣()