gpt4 book ai didi

javascript - 导航栏的 AngularJS 事件类不起作用

转载 作者:行者123 更新时间:2023-11-30 00:27:59 25 4
gpt4 key购买 nike

我是 AngularJS 的新手,所以我正在做一个实验。我想在转到新页面时更改导航的事件类。我想为此制作一个特定的 Controller 变量,HeaderCtrl是 Controller ,定义在app.js文件中:

'use strict';

/**
* @ngdoc overview
* @name ePortfolioApp
* @description
* # ePortfolioApp
*
* Main module of the application.
*/
var app = angular.module('ePortfolioApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/personality', {
templateUrl: 'views/personality.html',
controller: 'PersonalityCtrl'
})
.
when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCrl'
})
.when('/projects' ,{
templateUrl: 'views/projects.html',
controller: 'ProjectsCtrl'
})
.otherwise({
redirectTo: '/'
});
});

$rootScope.$on('$routeChangeStart', function (evt, next, currentRoute) {
$rootScope.isActive = next.$$route.routeName;
}
}

app.controller('HeaderCtrl', ['$scope', function($scope){
$scope.isActive = 'main';
}])

$rootScope.$watch('isActive', function() {
$scope.isActive = $rootScope.isActive;
});

我的 HTML 有以下代码:

<div class="collapse navbar-collapse" id="js-navbar-collapse">

<ul class="nav navbar-nav">
<li ng-class="isActive == 'main' ? 'active' : ' ' "><a href="#/">Home</a></li>
<li ng-class="isActive == 'about' ? 'active' : ' ' "><a ng-href="#/about">About</a></li>
<li ng-class="isActive == 'projects' ? 'active' : ' ' "><a ng-href="#/projects">Projects</a></li>
<li ng-class="isActive == 'personality' ? 'active' : ' ' "><a ng-href="#/personality">Personality</a></li>
<li ng-class="isActive == 'contact' ? 'active' : ' ' "><a ng-href="#/contact">Contact</a></li>
</ul>
</div>

怎么了?

最佳答案

基本上 next.$$route 返回定义在 $routeProvider 条件下的数组。为了使您的代码正常工作,您需要将 routeName 参数添加到您的每条 route ,这将使您的代码正常工作。

代码

$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
routeName: 'main'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
routeName: 'about'
})
.when('/personality', {
templateUrl: 'views/personality.html',
controller: 'PersonalityCtrl',
routeName: 'personality'
})
.
when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCrl',
routeName: 'contact'
})
.when('/projects' ,{
templateUrl: 'views/projects.html',
controller: 'ProjectsCtrl',
routeName: 'projects'
})
.otherwise({
redirectTo: '/'
});

此外,您需要将 $routeChangeStart 放在运行 block 中

app.run(function($rootScope){
$rootScope.$on('$routeChangeStart', function (evt, next, currentRoute) {
$rootScope.isActive = next.$$route.routeName;
}
})

Demo Plunkr

关于javascript - 导航栏的 AngularJS 事件类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30709354/

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