<ul> <li ng-repeat="(index, item) in headerList"> <a ui-sref="{{item.href}}" ng-class="{selected: selectedIndex === index}" ng-click="changeIndex(index)"> <span>{{item.name}}</span> </a> </li> </ul>
controller('headerCtrl', function($scope, $location, $state) { // 刷新時修正 selectedIndex var path = $location.$$path.split('/')[1]; switch(path) { case '': $scope.selectedIndex = 0; break; case 'book': $scope.selectedIndex = 1; break; case 'borrow': $scope.selectedIndex = 2; break; case 'reader': $scope.selectedIndex = 3; break; } // 這里的href指的是ui-router的state的name $scope.headerList = [{ href: 'home', name: '首頁' }, { href: 'book', name: '圖書管理' }, { href: 'borrow', name: '借還管理' }, { href: 'reader', name: '讀者管理' } ]; $scope.changeIndex = function(index) { $scope.selectedIndex = index; }; });
效果界面: