Search code examples
javascriptangularjsangularjs-ng-repeatdirectiveng-style

How to ng-style one element it's $index created by ng-repeat?


  • I have 2 directives: wa-hotspots & wa-tooltips.
  • On ng-mouseover of wa-hotspots it takes that $index of wa-hotspot and sets the visibility and position of wa-tooltip via ng-class:on and ng-style="tooltipCoords" by matching indexes.
  • Note: Since wa-hotspots & wa-tooltips share the same collection page.hotspots and therefore they share teh same index via ng-repeat

Problem: When you hover over wa-hotspots it sets the ng-style position to ALL of the elements in wa-tooltips. I only want it ot set the proper matching index. Since the visiblity is controlled by ng-class, This doesn't really matter but it seems like it's extra overhead that could be avoid.

Therefore:

Question: How can I make sure that my ng-style isn't styling all the wa-tooltips on hover of wa-hotspots? But rather, style only the tooltip that matches the proper shared index?

<ul id="wa-page-{{page.pageindex}}" class="wa-page-inner" ng-mouseleave="pageLeave()">


    <li wa-hotspots 
        <map name="wa-page-hotspot-{{page.pageindex}}">
            <area ng-repeat="hotspot in page.hotspots" 
                  class="page-hotspot" 
                  shape="{{hotspot.areashape}}" 
                  coords="{{hotspot.coordinatetag_scaled}}" 
                  ng-mouseover="showTooltip($index, hotspot.coordinatetag_scaled)" 
                  ng-mouseout="hideTooltip()">
        </map>
    </li>

    <li class="tooltip-wrapper">
        <ul class="tooltip">
            <li wa-tooltips 
                ng-repeat="hotspot in page.hotspots" 
                ng-class="{on: hovered.index == $index}" 
                ng-mouseover="hovered.active == true" 
                ng-mouseout="hovered.active == false" 
                ng-style="tooltipCoords" hotspot="hotspot">
            </li>
        </ul>
    </li>
</ul>

tooltip:


Solution

  • You need to make it per item like in your case - hotspot.tooltipCoords then set that variable by index. you can do the check inside the expression function.

    Heres a fiddle

    <div ng-controller="MyCtrl">
        <div ng-repeat="item in items" ng-style="isChecked($index)">
            name: {{item.name}}, {{item.title}}
            <input type="checkbox" ng-model="item.checked" /> 
       </div>
    </div>
    

    ...

    $scope.isChecked = function($index){
        var color = $scope.items[$index].checked ? 'red' : 'blue';
        return {color:color};
    }