2016-04-23 55 views
1

新手在angularjs。試圖學習一些新的東西。使用路由在角度js中設置活動菜單

我有一個簡單的頁面,當用戶導航到不同的頁面時,我需要在menuitem的相應li上設置active類。以下是我添加路線的方式。

angular.module('home', ["ngRoute"]). 
config(function ($routeProvider, $locationProvider) { 
    $routeProvider. 
     when('/home', { templateUrl: 'partials/home.html', controller: "homeController", activetab: "home" }). 
     when('/about', { templateUrl: 'partials/about.html', activetab: "about" }). 
     when('/gallery', { templateUrl: 'partials/gallery.html', activetab: "gallery" }). 
     when('/contact', { templateUrl: 'partials/contact.html', activetab: "contact" }). 
     when('/services', { templateUrl: 'partials/services.html', activetab: "services" }). 
     when('/house', { templateUrl: 'partials/house.html', activetab: "house" }). 
     otherwise({ redirectTo: '/home', templateUrl: 'partials/home.html', activetab: "home" }); 
    $locationProvider.html5Mode(true); 
}).controller("homeController", function ($scope, $http, $route) { 
    $scope.$route = $route; 
}); 

而且我將只有homecontroller這是隻有當用戶訪問主頁時綁定。其他頁面將只有靜態數據。

我添加ng-apphtml如下:

<html ng-app="home"> 

下面是如何我試圖active類添加到li

<ul class="nav navbar-nav"> 
    <li ng-class="{'active': $route.current.activetab == 'home'}"><a href="home">Home <span class="sr-only">(current)</span></a></li> 
    <li ng-class="{'active': $route.current.activetab == 'about'}"><a href="about">About</a></li> 
    <li ng-class="{'active': $route.current.activetab == 'services'}"><a href="services">Services</a></li> 
    <li ng-class="{'active': $route.current.activetab == 'house'}"><a href="house">The house</a></li> 
    <li ng-class="{'active': $route.current.activetab == 'gallery'}"><a href="gallery">Gallery</a></li> 
    <li ng-class="{'active': $route.current.activetab == 'contact'}"><a href="contact">Contact</a></li> 
</ul> 

但我在完成這個沒有運氣。即使導航發生,活動類也不會被添加。我跟着answer mentioned in this post。請讓我知道我還能做到這一點,或者我的錯誤是什麼?

回答

4

試試這個jsfiddle例子我做了,它不起作用的原因是你切換狀態後,你沒有權限訪問$route$route只能在您的homecontroller$scope中訪問,我認爲這隻適用於您的主頁。

+0

是的..這是問題所在。我遵循不同的方法,然後..我綁定了一個控制器索引頁面..現在它工作正常,並且也是太.. ..非常感謝.. –