javascript - angular active link navigation -


angular beginner here. i'm trying have link active once i'm on given page. found quite couple of examples none of work, must i'm doing wrong.

this i've been trying (controller) :

angular.module('myapp')   .controller('homectrl', ['$scope', function ($scope) {     $('body').addclass('homepage');      $scope.isactive = function(route) {       return route === $location.path();     }   }]); 

html :

<li "ng-class" = "{active:isactive('/') || isactive('/home')}">  home </li> <li "ng-class" = "{active:isactive('/about')}">  </li> <li "ng-class" = "{active:isactive('/contact')}">  contact </li> 

application :

var app = angular     .module('myapp', [         'nganimate',         'ngcookies',         'ngresource',         'ngroute',         'ngsanitize',         'ngtouch',         'templates',          'ng-token-auth'     ]).config(['$routeprovider', '$locationprovider', function ($routeprovider, $locationprovider) {         $routeprovider             .when('/home', {                 templateurl: 'home.html',                 controller: 'homectrl'             })             .when('/', {                 templateurl: 'home.html',                 controller: 'homectrl'             })             .when('/contact', {                 templateurl: 'contact.html',                 controller: 'contactctrl'             })             .when('/about', {                  templateurl: 'about.html',                  controller: 'aboutctrl'              })             .otherwise({               redirectto: '/'             });         $locationprovider.html5mode({           enabled: true,           requirebase: false         });     }]) 

so no matter on page i'm located at, ng-class nothing no errors in console. if home:

<li "ng-class" = "{active:true}">      home     </li> 

then active class on link, , output :

<li ng-class="{active:true}" class="active"> home </li> 

what doing wrong here? why doesn't interpolate function isactive should?

you cannot have logic check active link inside homectrl 1 of routes. when other routes loaded there no homectrl loaded.

there should controller defined outside ng-view, such rootctrl. isactive function should added it.

since child view scope have access parent scope, can use isactive in child views normally.

update: consider html

<body ng-controller='rootctrl'>    <div ng-view></div> </body> 

add isactive function on rootctrl.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -