在导航时使用angular设置变量

Set variable while navigating using angular

本文关键字:angular 设置 变量 导航      更新时间:2023-09-26

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

当我点击菜单时,它会导航到右边的页面。当我再次点击变量设置。但是可以在导航时设置变量吗?

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