ng-mouseover and leave to toggle item using mouse in angularjs
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
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;}
A little late here, but I've found this to be a common problem worth a custom directive to handle. Here's how that might look:
.directive('toggleOnHover', function(){
return {
restrict: 'A',
link: link
};
function link(scope, elem, attrs){
elem.on('mouseenter', applyToggleExp);
elem.on('mouseleave', applyToggleExp);
function applyToggleExp(){
scope.$apply(attrs.toggleOnHover);
}
}
});
You can use it like this:
<li toggle-on-hover="editableProp = !editableProp">edit</li>
I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
I'd probably change your example to look like this:
<ul ng-repeat="task in tasks">
<li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
<span ng-show="task.editable"><a>Edit</a></span>
</ul>
//js
$scope.enableEdit = function(item){
item.editable = true;
};
$scope.disableEdit = function(item){
item.editable = false;
};
I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.
Example jsFiddle.