What is the best way to apply ng-style to a single element that was generated using $index within an ng-repeat loop

  • I am dealing with 2 directives: wa-hotspots and wa-tooltips.
  • When the ng-mouseover event occurs on wa-hotspots, it takes the $index of wa-hotspot and adjusts the visibility and position of wa-tooltip using ng-class:on and ng-style="tooltipCoords" by matching the indexes.
  • Note: Since both wa-hotspots and wa-tooltips share the same collection named page.hotspots, they also share the same index through ng-repeat.

The Issue: The problem arises when hovering over wa-hotspots sets the ng-style position for ALL elements in wa-tooltips. I want it to set the style only for the corresponding matching index. Even though visibility is controlled by ng-class, this extra styling seems unnecessary and inefficient.

Hence:

Query: How can I ensure that my ng-style only styles the relevant tooltip that matches the shared index, rather than applying it to all wa-tooltips upon hovering over wa-hotspots?

<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:

Answer №1

To customize it for each item, you should use hotspot.tooltipCoords and set the variable by index. The check can be done within the expression function.

Here is a code snippet

<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};
}

Answer №2

Instead of

ng-mouseover="hovered.active == true" 
ng-mouseout="hovered.active == false"

use

ng-mouseover="hotspot.class== 'active'" 
ng-mouseout="hotspot.class== ''" 

and you can then utilize hotspot.class in ng-class as follows:

ng-class="hotspot.class"

Please refer to the demonstration below:

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.items = [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }, {
    id: 4
  }]

});
.red {
  background-color: yellow;
}
p {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">

    <p ng-repeat="i in items" ng-mouseover="i.class='red'" ng-class="i.class" ng-mouseout="i.class = ''">{{i.id}}</p>
  </div>
</div>

Answer №3

Check out the code snippet below:

<div class="col-md-4 col-xs-12 col-lg-4" ng-repeat="item in objects"> 
<button type="button" class="btn btn-sm pull-right" ng-class="item.style" ng-mouseover="item.style='newClass'" > 

Create a new class called "test" and swap out the ng-click event for ng-mouseover.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrasting behavior in JavaScript experienced in development versus production environments

I've been working on an application that, when given certain data, generates a diagram using JavaScript in conjunction with the kineticJS framework. During development, everything is smooth sailing, but once deployed to production (Heroku), things st ...

What is the best way to retrieve the offsetHeight of a Component Element using Vue.js?

I am currently working on a Vue.js component and successfully inserting it into the DOM. My goal is to find out its rendered height once it's in the DOM, specifically its offsetHeight. However, I seem to be missing something obvious as I can't fi ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

Troubleshooting Hover Problem with D3 Chord Example on Internet Explorer 11

I came across an interesting tutorial on how to create chord diagrams in D3, which I'm currently experimenting with. The tutorial can be found at One example that caught my attention is about hair color preferences. When you hover over a group on the ...

Conceal tab content by clicking outside of the tab or its contents

Here is an example of how Elementor tab works. When you click on a tab, the content section appears. I want to be able to close the content section by clicking on any other part of the page, except for the tabs and tab content themselves. This should not a ...

Yii2 pjax not refreshing properly when updating records in the gridview

I have successfully implemented functionality in my grid-view to control the number of rows displayed per page. This feature includes a drop-down menu with options such as 5, 10, 25, 50, and 100 rows. Whenever a user selects an option from the drop-down, I ...

Tips for always focusing on a textarea within an Angular UI modal when opening the modal

I am facing an issue with setting focus to a textarea within an angular ui modal. I need the focus to be set when the modal is made visible, but it cannot happen during document load as it only works the first time the modal opens. Furthermore, the modal ...

How to implement variables within the .map() function in JavaScript?

I am working on a map function where I need to pass in a variable as a Key to change the object item key to be based on that variable instead. For example, I want the obj.Salary below to actually represent the salary value when day equals "Day" instead o ...

Using ng-repeat to filter items within a select box

I'm currently working on updating my article list based on the selected category. I have no issues populating the list with articles, but I'm facing difficulties in populating the category select box and binding a function to its change event. B ...

"Consistent Behavior: jQuery ajax always triggers fail event, even when success is expected

My web page relies heavily on AJAX requests. Take a look at the following code snippet: function fetchSpecificData(start,end){ var link = createLink('open', start, end); getAjaxResponse(link).done(function(data) { //store data in ...

What steps do I need to take to have Greasemonkey execute a function upon the completion of an AJAX call

Whenever I select the trending tab on YouTube, an AJAX call is triggered to retrieve the latest trending videos. I have developed a custom script that filters out any videos I have already watched. Although this script successfully applies to the homepag ...

Switch the background image of a div when hovering over a different div that is not its parent or sibling

I am in the process of building a dynamic portfolio on WordPress and I need some help with a specific functionality. At the top of my page, I have a large banner image, followed by individual thumbnails of my work below. What I want to achieve is the abili ...

AngularJS - The Joy of Nested States

When utilizing nested states with UI Router, it is important to navigate through the nested states in order for them to function properly. For example: If you have: .state('home', { url: '/', templateUrl: 'home.html' ...

Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this: <div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" :value="item.title"> </div> ...

Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays wo ...

JavaScript newbie diving into the revealing module pattern

Currently diving into Addy Osmani's fantastic read on javascript design patterns, however, I'm facing a roadblock. Can someone help me identify the issue with my approach? (I'm experimenting with Raphael for fun): var myPaper = Raphael(&apo ...

Restricting JQuery pop-up to be shown only once

I'm looking for a solution to have a pop-up appear only once when the mouse leaves the screen. I'm not very experienced with coding, so I'm struggling to figure out how to achieve this. // Implementing Exit Intent function addEvent(obj, ev ...

Retrieving the elapsed time in seconds from a timer function and displaying it in my

I'm looking to transfer the minutes and seconds from my template's timer to my view. I've experimented with various approaches using an ajax.post request, but it hasn't quite worked as expected. Here is a snippet of my template code: ...

Troubleshooting error: Unable to access property 'post' in Angular Service when using $http

As I delve into learning Angular, my approach involves shifting all the business logic to services. However, I encountered an error while attempting a post request within a service: Cannot read property 'post' of undefined Provided below is a ...