Javascript 使用角度导航时设置变量

Javascript 使用角度导航时设置变量,javascript,angularjs,Javascript,Angularjs,我试图创建一个导航栏,但我被这段代码卡住了 当我单击它导航到右侧页面的菜单时会发生什么。当我再次单击时,变量被设置。但是,是否可以在导航时设置变量 <div> <nav class="{{active}}" > <!-- When a link in the menu is clicked, we set the active variable --> <a href="#/" class="home" ng

我试图创建一个导航栏,但我被这段代码卡住了

当我单击它导航到右侧页面的菜单时会发生什么。当我再次单击时,变量被设置。但是,是否可以在导航时设置变量

<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>

您可以通过监听位置更改并使用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>

谢谢你的回复,但我不能让它工作我添加了一个控制台日志到你的范围,当我点击我可以看到范围是活动的,等于我点击的页面。但是collor没有改变,在导航栏中我编辑了我的问题,也许你可以看到哪里出了问题。所以,你想做的是突出显示所选页面?这就是我想做的。但我不明白我怎么能做到这一点。我也在问题中添加了css谢谢。现在我有了一些可以使用的代码。
.active, .active:focus{
    color: red;
}
  <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>
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];
    });
});