Shaohao Lin Shaohao Lin - 1 month ago 17
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

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

HTML

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


this will give me somthing like:

<div>Facebook</div>
<div>Flickr</div>
<div>Google+</div>
<div>Instagram</div>
<div>Linkedin</div>


And my JS file:

$scope.socialArray = [
{name:"Facebook", color:"#3B5998"},
{name:"Flickr",color:"#FE0883"},
{name:"Google+",color:"#C63D2D"},
{name:"Instragram",color:"#4E433C"},
{name:"Linkedin",color:"#4875B4"}
];


My css:

.change-color{
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

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.addClass('change-color');
              element.css('background-color', $scope.colorcode);
          });
          element.on('mouseleave', function () {
              element.removeClass('change-color');
              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">{{social.name}}</div>

I made a JSFIDDLE Demo

Comments