AngularJS 製作頁籤

頁籤也是在一般網頁很常用到的 UI ,不過 Angular 實作起來跟 jQuery 差好多阿..

首先準備 html
  1. <div ng-controller="tabController" class="wrapper">  
  2.     <ul class="clearfix">  
  3.                 <li ng-repeat="tab in tabs"    
  4.                 ng-class="{active:isActiveTab(tab.url)}"    
  5.                 ng-click="onClickTab(tab)">{{tab.title}}</li>  
  6.     </ul>  
  7.     <div id="mainView">  
  8.         <div ng-include="currentTab"></div>  
  9.     </div>  
  10.     <script type="text/ng-template" id="one.tpl.html">  
  11.         <a href="http://www.flickr.com/photos/deathhell/6861320435/" title="Flickr 上 紅色死神 的 Cutman"><img src="http://farm8.staticflickr.com/7205/6861320435_87faa1786a.jpg" width="500" height="500" alt="Cutman"></a>  
  12.     </script>  
  13.     <script type="text/ng-template" id="two.tpl.html">  
  14.         <a href="http://www.flickr.com/photos/deathhell/6861320497/" title="Flickr 上 紅色死神 的 Gutsman"><img src="http://farm8.staticflickr.com/7193/6861320497_f9b2492d24.jpg" width="500" height="500" alt="Gutsman"></a>  
  15.     </script>  
  16.     <script type="text/ng-template" id="three.tpl.html">  
  17.         <a href="http://www.flickr.com/photos/deathhell/6861320569/" title="Flickr 上 紅色死神 的 Iceman"><img src="http://farm8.staticflickr.com/7038/6861320569_36165752d5.jpg" width="500" height="500" alt="Iceman"></a>  
  18.     </script>  
  19.     <script type="text/ng-template" id="four.tpl.html">  
  20.         <a href="http://www.flickr.com/photos/deathhell/6861320811/" title="Flickr 上 紅色死神 的 Fireman"><img src="http://farm8.staticflickr.com/7064/6861320811_c9343a33e2.jpg" width="500" height="500" alt="Fireman"></a>  
  21.     </script>  
  22. </div>  

簡單說就是用 text/ng-template 來依各分頁做樣板,然後在點 tab 的時候各別去顯示該顯示的內容。

javascript 部分
  1. function tabController($scope){   
  2.     $scope.tabs = [{   
  3.         title: 'Cutman',   
  4.         url: 'one.tpl.html'  
  5.     }, {   
  6.         title: 'Gutsman',   
  7.         url: 'two.tpl.html'  
  8.     }, {   
  9.         title: 'Iceman',   
  10.         url: 'three.tpl.html'  
  11.     }, {   
  12.         title: 'Fireman',   
  13.         url: 'four.tpl.html'  
  14.     }];   
  15.            
  16.     $scope.currentTab = 'one.tpl.html';   
  17.   
  18.     $scope.onClickTab = function (tab) {   
  19.             $scope.currentTab = tab.url;   
  20.     }   
  21.            
  22.     $scope.isActiveTab = function(tabUrl) {   
  23.             return tabUrl == $scope.currentTab;   
  24.     }   
  25. }  

Demo

參考
AngularJS: Simple Tabs

留言