我试图创建一个导航栏,但我陷入了这段代码。

当我单击菜单时,它将导航到正确的页面。当我再次单击时,将设置变量。但是可以在导航时设置变量。

<div>

    <nav class="{{active}}" >

        <!-- When a link in the menu is clicked, we set the active variable -->

        <a href="#/" class="home" ng-click="active='home'">Home</a>
        <a href="#/second" class="projects" ng-click="active='1234'">Projects</a>
        <a href="#/third" class="services" ng-click="active='services'">Services</a>
    </nav>

    <p ng-hide="active">Please click a menu item</p>
    <p ng-show="active">You chose <b>{{active}}</b></p>

</div>


编辑

我将标题页更改为此,但是我仍然可以使其正常工作。

<div>

    <nav ng-controller="testController" class="{{active}}">

        <!-- When a link in the menu is clicked, we set the active variable -->

        <a href="#/" class="home" >Home</a>
        <a href="#/second" class="second" >second</a>
        <a href="#/third" class="third" >third</a>

    </nav>


</div>


的CSS

nav.home .home,
nav.second .second,
nav.third .third{
    background-color:#e35885;
}

最佳答案

您可以通过侦听位置变化并使用ng-class指令来实现:

CSS:

.active, .active:focus{
    color: red;
}


HTML:

  <div ng-app="testApp">
        <div ng-controller="testController">
            <div>
                <!-- When a link in the menu is clicked, we set the active variable -->
                <a href="#/" ng-class="isPageSelected('Home')">Home</a>
                <a href="#/second" ng-class="isPageSelected('Second')">second</a>
                <a href="#/third" ng-class="isPageSelected('Third')">third</a>
            </div>
        </div>
</div>


Javascript:

var app = angular.module('testApp', []);
app.controller('testController', function ($scope, $location, $rootScope, $log) {
    $scope.locationsDescriptions = {
        '#/': 'Home',
        '#/second': 'Second',
        '#/third': 'Third'
    }
    $scope.isPageSelected = function (pageName) {
        return $scope.active == pageName ? 'active' : '';
    }
    $scope.$on("$locationChangeSuccess", function (event, next, current) {
        var location = this.location.hash.toLowerCase();
        $scope.active = $scope.locationsDescriptions[location];
    });
});

09-27 09:39