1

Fairly new to AngularJS and I'm also using Bootstrap CSS.

I have a main page and I'm using ngRoute to load html templates. I want the active navigation tab to change color whenever new template is loaded

I have something like

<div class="nav">
    <ul>
      <li><a href="#/">HOME</a></li>
      <li><a href="#about">ABOUT</a></li> 
      .....

$routeProvider
    .when('/', {
        templateUrl : 'home.html',
        controller  : 'mainCtrl',
    })
    .when('/about', {
        templateUrl : 'about.html',
        controller  : 'mainCtrl',
    })

I've seen some answers where you dynamically add/remove 'active' class and yes that worked for me but I want custom color.

I generate a random color and save it in $scope.randomColor. I want to use that color as active color.

I have a directive that simply changes the color for active and hover. I wish I could just add and remove those to anchor tags based on which page a user is looking at.

.directive('ngHover', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
        element
        .on('mouseenter',function() {
            element.css('color', scope.backgroundColor);
        })
        .on('mouseleave',function() {
            element.css('color','#333');
        });
    }
  }
})
.directive('ngActive', function() {
  return {
    restrict: 'A',
    link: function(scope, element) {
        element.css('color', scope.backgroundColor);
    }
  }
});

Anyone have an idea how to achieve what I want to do? It seems so easy to do with Jquery but I'm learning Angular so I want to use that only if possible.

Edit

I tried adding 'active' class method but also changed the color of active class

var el = document.getElementsByClassName("active");    
var wrappedEl = angular.element(el);
wrappedEl.css('color', $scope.backgroundColor)

This seems to work but whenever I go to different tab, active class is removed from but color remains the same? weird..

EDIT2

Oh wait that was dumb lol Solved it by adding style manually like suggested here

Dynamically change a css class' properties with AngularJS

Community
  • 1
  • 1
TKP
  • 443
  • 1
  • 9
  • 19

1 Answers1

0

Use ngstyle, here is the documentation; https://docs.angularjs.org/api/ng/directive/ngStyle

Frederick Mfinanga
  • 1,045
  • 1
  • 10
  • 27