Reputation: 8706
I have a router, when some route is active - I show correct template. But my navigation menu is not in sync with this.. What is the proper way to sync navigation menu with router?
I've thought about NavigationCtrl
, but I need special service, that will be a layer between other controllers and nav...
Currently my navigation is something like that:
var app = angular.module('Money', []);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'general.html',
controller: 'GeneralCtrl'
})
.when('/accounts', {
templateUrl: 'accounts.html',
controller: 'AccountsCtrl'
});
}]);
app.controller('NavigationCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
// nothing right now
}]);
app.controller('GeneralCtrl', ['$scope', function ($scope) {
$scope.model = {
title: 'General page!'
};
}]);
app.controller('AccountsCtrl', ['$scope', function ($scope) {
$scope.model = {
title: 'Accounts page!'
};
}]);
<div id="app" ng-app="Money">
<div class="navbar navbar-inverse" ng-controller="NavigationCtrl">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".navbar-responsive-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">My money</a>
<div class="nav-collapse collapse navbar-responsive-collapse">
<ul class="nav">
<li class="active"><a href="#">General</a></li>
<li><a href="#accounts">Accounts</a></li>
</ul>
<ul class="nav pull-right">
<li><a href="/logout">Sign out</a></li>
</ul>
</div><!-- /.nav-collapse -->
</div>
</div><!-- /navbar-inner -->
</div>
<ng-view></ng-view>
</div>
Upvotes: 1
Views: 3358
Reputation: 6366
-Edit-
Ben Nadel did a great job explaining Mapping AngularJS Routes Onto URL Parameters And Client-Side Events, so why reinvent the wheel?
Here's the gist in full.
Line 166 is the function that updates the variables that are used in the ng-class
values of the navigation items on Line 44.
You can use ng-class
in conjunction with a function that checks a $scope
variable you update—presumably when you change routes.
$scope.isActive = function (url) {
if (url == "#" + $scope.activeRoute) {
return "on";
} else {
return "off";
}
};
<ul class="nav" ng-cloak>
<li ng-repeat="button in navigation" ng-class="isActive(button.url)">
{{button.text}}
</li>
</ul>
Upvotes: 1