在 Angular 中,在两个不同的指令之间传达匹配的$index

In Angular, Communicating a matching $index between two different directives

本文关键字:之间 指令 index Angular 两个      更新时间:2023-09-26

我有两个指令:

<wa-svg ng-repeat="page in Pages" ng-mouseover="showTooltip($index)>
<wa-tooltip ng-repeat="page in Pages" ng-class="{on: matchedIndex}">

问题:

将鼠标悬停在特定wa-svg上时,如何匹配wa-svg$index以使wa-tooltip matchedIndex返回 true。 因此,on类被附加到wa-tooltip

我相信这将需要一个孤立的范围,或者可能通过ng-model但这令人困惑。

注意:我无法嵌套这些元素,因为wa-svg是一个svg对象,除非使用foreignObject和等等,否则你不能很好地嵌套。

嗯,

那么共享控制器怎么样?

具有此功能的包装控制器:

  $scope.showTooltip= function($index) {
       $scope.hoveredIndex = $index;
  }

在您的工具提示指令中执行以下操作:

  <wa-tooltip ng-repeat="page in pages" ng-class="{on: $index === hoveredIndex}">

这对你有用吗?

这应该有效:

<div ng-init="hovered = {}">
  <wa-svg ng-repeat="page in Pages" ng-mouseover="hovered.index = $index" />
  <wa-tooltip ng-repeat="page in Pages" ng-class="{on: hovered.index == $index}" />
</div>

总结一下:将鼠标悬停在wa-svg上会设置hovered.index,您可以在 wa-tooltip 中访问该 。

hovered = {}部分的唯一原因是转发器会创建新的作用域,因此我在新作用域之外创建了一个对象,以便可以从两个转发器访问索引。 您可以/应该将该语句放入控制器中。