17

Am trying to add a class (blue) to a button when ever you hover the button using AngularJS.

HTML

<button class="btn-add-optimize" ng-mouseover="hover(iets)">Add and Optimize</button>

AngularJS

$scope.hover = function (iets) {
    var Dit = this;
    Dit.add("blue");
};

Anyone can help me out? Preferable a small example, it would be very appreciated!

3
  • 2
    Why not just use css? .btn-add-optimize:hover {color: blue;} Commented Dec 9, 2014 at 5:05
  • I would highly advise using css, as well. Using angular for such functionality is going way over the top. Commented Dec 9, 2014 at 5:54
  • Thank you Blue, I end up using your solution :) Commented Dec 9, 2014 at 22:54

3 Answers 3

44

I've used something like this with success:

<button
    ng-class="{'some-class':hovering}"
    ng-mouseenter="hovering=true"
    ng-mouseleave="hovering=false">Add and Optimize</button>

Entering and leaving the button toggles $scope.hovering, and the application of some-class is contingent on the $scope.hovering scope variable being true.

Sign up to request clarification or add additional context in comments.

2 Comments

Using the CSS :hover pseudo-attribute should work for most cases, but if you want to use it to trigger other behaviors on the page as well, this will work nicely.
I had to write a directive for it, in my case i was doing it basically on all card likes elements wich was repetitive. github.com/guilhermegeek/pi-angular-class-hover
14
<button
ng-class="{'some-class':hovering}"
ng-mouseenter="hovering=true"
ng-mouseleave="hovering=false">Add and Optimize</button>

You should use this form : ng-class

2 Comments

can't understand why people gave you 9 up votes when you just used the very same answer above you.
@msqar At the time, Ercan's answer was technically correct and Collin's contained a bug, even though it was otherwise correct and identical. Feel free to review my edit to solve said bug.
0

For Angular 8, this works for me:

<nav id="sidebar" [class]="!hovered ? 'active': ''" (mouseenter)='hovered=true' (mouseleave)="hovered=false">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.