我是AngularJS的新手,所以我正在做一个实验。当我转到新页面时,我想更改导航的活动类。我想为此设置一个特定的控制器变量,
HeaderCtrl是控制器,在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
参数,这将使您的代码正常工作。
码
$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
放在运行块中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/