Angular 的 tab

總覺得好像一直在寫 tab ,實在是還沒搞通,搞通以後就快了。

HTML 長這樣
  1. <div ng-app="plunker">  
  2.     <ul ng-controller="MainCtrl" class="nav">  
  3.       <li ng-repeat="item in collection"  
  4.              ng-class="{ 'active': $index == selectedIndex }"  
  5.              ng-click="itemClicked($index)">  
  6.         {{ item }}   
  7.       </li>  
  8.     </ul>  
  9. </div>  

主要的是希望在 click 後根據 click 的 index 去切換 css。

js 長這樣
  1. var app = angular.module('plunker', []);   
  2.   
  3. app.controller('MainCtrl'function($scope) {   
  4.   $scope.collection = ["Item 1""Item 2""Item 3"];   
  5.      
  6.   $scope.selectedIndex = 0;   
  7.      
  8.   $scope.itemClicked = function ($index) {   
  9.     console.log($index);   
  10.     $scope.selectedIndex = $index;   
  11.   }   
  12. });  

在 click 的時候把 selectedIndex 指給 $index ,再切換 css 就完成了。

Demo

留言