Reputation: 769
I try to explain my problem in advance sorry for my bad english.
I have written code with angular and angular route My navbar looks like this in html
<ul nav-menu>
<li><a href="">Index</a></li>
/*others*/
</ul>
And route params
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'mainCtrl'
})
.when('/skills', {
// others
})
Everything works perfectly but my questin is:
How can I set some css to my li
element when route has been loaded or active?
Upvotes: 0
Views: 2065
Reputation: 103
This is pretty easy with Angular.
You can define a controller for the NavBar as below,
<ul nav-menu ng-controller="NavbarCtrl">
<li ng-class={active : isRouteActive("/home")}><a href="/home">Index</a></li>
</ul>
Then your controller should defined as below,
app.module("myApp",["ngRoute"])
.controller("NavbarCtrl", function($scope, $location) {
$scope.isRouteActive = function(route) {
var curRoute = $location.path();
return curRoute.match(route);
}
});
If you are using UI Router it's just a matter of adding an attribute like below,
<ul class="nav navbar-nav">
<li ui-sref-active="active"><a ui-sref="home">Home</a></li>
<li ui-sref-active="active"><a ui-sref="about">About</a></li>
</ul>
This will make the item highlighted automatically when the current state matches.
Hope this helps
~Ragesh
Upvotes: 1
Reputation: 202
In controller that is attach to menu, inject $state
. This will give information about state You are in right now. ng-class="active: $state === actual_state_name"
will set active class . I guess after inject You can use $state in view, but You need to check it by Yourself.
Another solution, not in angular way is getting javascript window
object. Similar is $location, whitch provide info about actual link and other cool features
Upvotes: 0
Reputation: 365
In angular UI there's a component (Angular UI) that checks whether the route is currently active or not: Here's an example from its documentation: Angular-UI Utils
<a ui-route="/page" ng-class="{active: $uiRoute}">link</a>
What it simply means is, when the route in the ui-route is currently accessed, the class active should be enabled.
If you wanna do it using angular only, you can do it like this.
<li><a ng-href="/home" ng-class="{'active: $location.path() ==='/home'}">Home</a></li>
Upvotes: 0
Reputation: 4319
You have to deal with more than topic here.
- First, have a look at ngClass. There you can put Angular logic inside the class, so it's changing with the scope values or function returns.
- Therefore you have to deal with passing scopes and data through controllers, or depending how your app is structured.
For the second topic, here is a good SO question/answer which explains it pretty well.
Upvotes: 0