gpt4 book ai didi

javascript - 使用 Angular 导航时设置变量

转载 作者:行者123 更新时间:2023-12-02 15:44:02 24 4
gpt4 key购买 nike

我正在尝试创建一个导航栏,但我被这段代码困住了。

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

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

关于javascript - 使用 Angular 导航时设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com