user3398172 user3398172 - 6 months ago 136
jQuery Question

ng-mouseover and leave to toggle item using mouse in angularjs

HTML:

<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>


JS:

$scope.hoverIn = function(){
$scope.hoverEdit = true;
};

$scope.hoverOut = function(){
$scope.hoverEdit = false;
};


The code is ridiculous because I think it's too much. I think it can be simplified. Anyway the result toggle all the item once it's hovered. I've jQuery background, so I have no idea how to make single item work in
ng-repeat
.

Answer

Angular solution

You can fix it like this:

$scope.hoverIn = function(){
    this.hoverEdit = true;
};

$scope.hoverOut = function(){
    this.hoverEdit = false;
};

Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.

Also you need to put ngRepeat on li:

<ul>
    <li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
        {{task.name}}
        <span ng-show="hoverEdit">
            <a>Edit</a>
        </span>
    </li>
</ul>

Demo: http://plnkr.co/edit/eGohFqiGKmkonmLwT3g1?p=preview

CSS solution

However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:

ul li span {display: none;}
ul li:hover span {display: inline;}