我对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>
有什么问题?
答案 0 :(得分:1)
基本上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;
}
})
答案 1 :(得分:0)
ng-class="{ active: $state.includes('contacts') }"