CSS 角度:在悬停时更新范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15772510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular: updating scope on hover
提问by plus-
I'd like some child div of a main div be hidden by default an visible when you hover over the main div.
当您将鼠标悬停在主 div 上时,我希望主 div 的某些子 div 默认隐藏并可见。
I'm trying to have that native in angular and forget the .hover()
way in jquery.
我试图在 angular 中使用本机并忘记.hover()
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?
我想ng-show
在子 div 上使用,然后在我悬停主 div 时更新绑定。是否有监听悬停的指令?
回答by Josh David Miller
You're on the right track. You can actually use the ngMouseenter and ngMouseleave directives to do this.
你在正确的轨道上。您实际上可以使用 ngMouseenter 和 ngMouseleave 指令来执行此操作。
<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
这是一个工作的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.
@Swordfish0321 也是正确的 - 如果您愿意,您可以编写一个非常简单的指令来专门监听悬停,但这可能没有必要。例如,我们在UI Bootstrap 中使用mouseenter
和mouseleave
作为工具提示。
回答by Chev
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.
感谢@JoshDavidMiller 提供了一个非常简洁的答案。我需要在 ng-repeat 中做到这一点,但无法找到一种优雅的方式来做到这一点。在范围上使用布尔值显示列表中所有元素的编辑控件,而不仅仅是我悬停的元素。我几乎弯下腰来鞭打angular.element
(即 JQuery)并自己附加悬停处理程序,以便他们可以手动仅显示悬停元素的控件。我很高兴我没有屈服于这种邪恶的方式。
<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.
只需将该属性附加到item
而不是$scope
。在某些情况下,我无法向列表中的项目添加随机键,因此我将数组映射到一个新数组,其中item
它实际上是包装器对象上的一个属性,然后我可以将我想要的任何属性附加到包装器对象,而无需污染item
钥匙。