Shaohao Lin Shaohao Lin - 9 months ago 75
AngularJS Question

Angular hover effect on change background color with dynamic color code

I want to have hover effect on a div to change the color based on the color code I passed to. My idea is to pass color code to a directive and then call

. However, I also need to add the hover class to the particular div using
. Now, I got stuck because I don't know how to approach this.


<div ng-repeat="social in socialArray">{{}}</div>

this will give me somthing like:


And my JS file:

$scope.socialArray = [
{name:"Facebook", color:"#3B5998"},

My css:

transition: 0.4s all;

.change-color:hover, .change-color:focus, .change-color:active{
color: #fff;
background-color: #e38d13;
cursor: pointer;

I want to be able to change the background-color dynamically based on the color I have in the socailArray. Any suggestion or hint will be awesome. Thank you in advanced!

Answer Source

After researched a while, I got it work by making a directive binding with colorcode. Angular JS directive:

angular.module('myApp', [])
 .directive('changeBackground', ['$animate', function ($animate) {
    return {
      restrict: 'EA',
      scope: {
          colorcode: '@?'
      link: function ($scope, element, attr) {
          element.on('mouseenter', function () {
              element.css('background-color', $scope.colorcode);
          element.on('mouseleave', function () {
              element.css('background-color', '#fff');

And in the HTML file will look like this:

<div change-background colorcode="{{social.color}}" ng-repeat="social in socialArray">{{}}</div>

I made a JSFIDDLE Demo