不知道什麼是 Bootstrap 的 Grid system 可以 >>看這邊<<
比較複雜的是 要如何用 AngularJS 現有的 directive 來組成一個可變動的 Grid
因為我不想直接用程式刻,所以都是通過 template 以及像是 ng-if,ng-init 以及 ng-repeat 這些 directive 來達成
當然實作的方式有好有壞啦,用程式刻我認為會稍微地好理解
但是你如果能充分利用原有的 direcitve 搭配 template 或許會讓你對 AngularJS directive 的開發更容易掌握
下圖是這次範例實作出來的結果(將所有的 products 以 grid system 呈現,每列三欄):
首先把我把 directive 分成 productContainer (表示整個 Grid system 的 directive)
以及 productRow (表示 Grid system 中的每一列的 directive)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module("demoApp", []) | |
.directive("productContainer", function(){ | |
return{ | |
scope:{ | |
data: "=" | |
}, | |
templateUrl: "productsTemplate.html", | |
link: function(scope, el, attr){ | |
// splitSize 表示每列有幾個 product | |
scope.splitSize = parseInt(attr["splitSize"]); | |
}, | |
restrict: "AE" | |
}; | |
}).directive("productRow", function(){ | |
return{ | |
scope: {}, | |
templateUrl: "productRowTemplate.html", | |
link: function(scope, el, attr){ | |
scope.data = scope.$eval(attr.rowData); | |
}, | |
restrict: "E" | |
}; | |
}); |
接下來就是這兩個 directive 對應的 template 程式,最複雜的就是 productsTemplate.html 了
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div ng-repeat='product in data' | |
ng-init="remainder= $index % splitSize; match= remainder == splitSize-1;"> | |
<div class='row' ng-if='match' ng-init="data= data.slice($index-(splitSize-1), $index+1)"> | |
<product-row row-data="{{data}}"></product-row> | |
</div> | |
<div class='row' ng-if='$last && !match' ng-init="data= data.slice($index-remainder, $index+1)"> | |
<product-row row-data="{{data}}"></product-row> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class='col-md-4' ng-repeat='product in data'> | |
<div class='well'> | |
{{product.name}} | |
</div> | |
</div> |
最後就是這個 directive 使用的部分
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div ng-controller="ProductController" class="col-md-offset-4 col-md-4"> | |
<product-container data="products" split-size="3"></product-container> | |
</div> |
沒有留言:
張貼留言