使用angular导航时设置变量

时间:2015-09-03 08:13:34

标签: javascript angularjs

我正在尝试创建一个导航栏,但我对此代码感到困惑。

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

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

1 个答案:

答案 0 :(得分:2)

您可以通过收听位置更改并使用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];
    });
});