angular: updating scope on hover

All we need is an easy explanation of the problem, so here it is.

I’d like some child div of a main div be hidden by default an visible when you hover over the main div.

I’m trying to have that native in angular and forget the .hover() way in jquery.

I though about using ng-show on the child div and then updating the binding when I hover the main div. Is there a directive to listen for hovering?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You’re on the right track. You can actually use the ngMouseenter and ngMouseleave directives to do this.

<span ng-mouseenter="show = true" ng-mouseleave="show = false">
  Mouse over me.
</span>

<div ng-show="show">Hello!</div>

Here’s a working Plunker: http://plnkr.co/edit/Ro80nR7HT7OGGPCXjz7E?p=preview

@Swordfish0321 is also right – you can write a very simple directive to listen specifically for the hovering if you’d like, but it may not be necessary. We use mouseenter and mouseleave for tooltips in UI Bootstrap, for example.

Method 2

Thanks to @JoshDavidMiller for a very succinct answer. I had a need to do this in an ng-repeat and couldn’t quite figure out an elegant way to do it. Using a boolean on the scope was showing the edit controls for all elements in the list instead of just the one I was hovering over. I almost stooped to whipping out angular.element (i.e. JQuery) and attaching hover handlers myself so they could manually show just the controls for the hovered element. I am glad I didn’t stoop to such evil ways.

<div ng-repeat="item in items" ng-mouseenter="item.showEdit = true" ng-mouseleave="item.showEdit = false">
    <span class="glyphicon glyphicon-edit" ng-show="item.showEdit"></span>
    Mouse over me.
</div>

Simply attach the property to the item rather than $scope. In a few situations I couldn’t add random keys to the items in my list so I mapped my array to a new one where the item is actually a property on a wrapper object, then I could attach any properties I wanted to the wrapper object without polluting the item keys.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply