Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular: updating scope on hover

Tags:

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?

like image 849
plus- Avatar asked Apr 02 '13 19:04

plus-


2 Answers

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.

like image 108
Josh David Miller Avatar answered Oct 07 '22 18:10

Josh David Miller


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.

like image 27
Chev Avatar answered Oct 07 '22 18:10

Chev