0

I have a background image on a div that I want to have switch on hover. I can't change the class because I'm using a bound property to fill in the information. As far as I know I don't see any way to add hover with styles inside of the html and I found a way to do it in jquery but it just doesn't seem like the angular way.

||||||
  • 3
    Could you provide the code u are having now, so we can see your wrong output? – MiKE Feb 8 '14 at 1:22
8

Method #1: No controller, everything in template.

<div ng-init="bg = ''" 
    ng-mouseenter="bg = 'http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100'" 
    ng-mouseleave="bg = ''" 
    style="background-image: url({{bg}});">
</div>

Method #2: Using vars to store the values (uses a controller)

<div ng-mouseenter="bg = imageOn" 
    ng-mouseleave="bg = imageOff" 
    style="background-image: url({{bg1}});">
</div>

Controller:

function myCtrl($scope){
    $scope.bg1 = "" // this is the default image.
    $scope.imageOn = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
    $scope.imageOff = ""; // image that would after after the mouse off.
}

Method #3: Saved the best for last! Using a directive!!

<div hover-bg-image="{{image}}"></div>

Directive (could be improved to revert back to original image if there is one... its basic to show example):

.directive('hoverBgImage',function(){
    return {
        link: function(scope, elm, attrs){
            elm.bind('mouseenter',function(){
                this.style.backgroundImage = 'url('+attrs.hoverBgImage+')';
            });
            elm.bind('mouseleave',function(){
                this.style.backgroundImage = '';
            })
        }
    };
});

Controller:

function withDirective($scope){
    $scope.image = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
}

Note: The items in the controllers could/should/would be set dynamically.

Demos: http://jsfiddle.net/TheSharpieOne/kJgVw/1/

||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.