ng-mouseover 并离开以在 angularjs 中使用鼠标切换项目 [英] 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;
};
代码很可笑,因为我认为它太多了.我认为可以简化.无论如何,一旦悬停,结果就会切换所有项目.我有 jQuery 背景,所以我不知道如何在 ng-repeat
中使单个项目工作.
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
.
推荐答案
Angular 解决方案
你可以这样修复它:
Angular solution
You can fix it like this:
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
在 ngMouseover(和类似的)函数内部,上下文是当前项作用域,因此它指的是当前子作用域.
Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.
还需要将 ngRepeat
放在 li
上:
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>
但是,如果可能,请尝试仅使用 CSS 执行此类操作,这将是最佳解决方案,并且不需要 JS:
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;}
这篇关于ng-mouseover 并离开以在 angularjs 中使用鼠标切换项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!