My Angular app has several views. The index.html
file which has the <div ng-view></div>
also has a header/navbar that has links to each of these views.
The $routeProvider
is configured to load respective views and their controllers.
Considering this setup, where each of the views has its own controller, how do I add CSS class="active"
to the appropriate link in the header when navigating within the app?
Extra Info.:
I added ng-click="set_page_id(x)"
and ng-class={active: active_page_id === x}
to the links and realized there's no controller associated with the index.html
. I wrote a jQuery function to make this work by listening to click events but it doesn't work when a view itself calls another view. I wonder if there's a better, Angular way.
My Angular app has several views. The index.html
file which has the <div ng-view></div>
also has a header/navbar that has links to each of these views.
The $routeProvider
is configured to load respective views and their controllers.
Considering this setup, where each of the views has its own controller, how do I add CSS class="active"
to the appropriate link in the header when navigating within the app?
Extra Info.:
I added ng-click="set_page_id(x)"
and ng-class={active: active_page_id === x}
to the links and realized there's no controller associated with the index.html
. I wrote a jQuery function to make this work by listening to click events but it doesn't work when a view itself calls another view. I wonder if there's a better, Angular way.
- 1 The $rootScope object is recognized on the whole application, including the index.html page. Have you tried using that? – user3063182 Commented Jul 31, 2014 at 22:23
- If I'm not mistaken, that'll provide me a means to share data betwixt controllers. That can be done using a global variable as well. How do I conditionally do something on the index.html page is my problem. – Karma Commented Jul 31, 2014 at 22:44
1 Answer
Reset to default 4You have your main or nav controller with something like:
app.controller('mainCtrl', function($scope, $rootScope, $location) {
$scope.menu = [
{label:'Home', route:'/'},
{label:'About', route:'/about'},
{label:'Contact', route:'/contact'}
]
$scope.menuActive = '/';
$rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
$scope.menuActive = $location.path();
});
});
Then
<li ng-repeat="item in menu" ng-class="{active: item.route == menuActive }"><a href="#{{item.route}}" >{{item.label}}</a> </li>
Heres a Plunker
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745139357a4613356.html
评论列表(0条)