【问题标题】:setting active menu in angular js with routing使用路由在 Angular js 中设置活动菜单
【发布时间】:2016-08-16 20:46:18
【问题描述】:

angularjs 的新手。尝试学习一些新东西。

我有一个简单的页面,当用户导航到不同的页面时,我需要在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-app 添加到我的html,如下所示:

<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。请让我知道我还能如何实现这一目标或我的错误是什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    试试我做的这个jsfiddle的例子,它不起作用的原因是你切换状态后,你无权访问$route$route 只能在您的homecontroller$scope 中访问,我假设它仅适用于您的主页。

    【讨论】:

    • 是的..这就是问题所在。然后我采用了不同的方法..我将控制器绑定到索引页面..现在它工作正常,而且也可以..非常感谢..
    猜你喜欢
    • 2021-05-23
    • 2023-02-05
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2013-04-19
    • 2016-12-13
    相关资源
    最近更新 更多