What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I want it to fade with a button for interaction. However, there seems to be an issue as the hover effect affects all images instead of just the one being hovered over. I've used ng-mouseenter and ng-mouseleave for this functionality, but it's not behaving as expected. Any help to troubleshoot this would be highly appreciated! Below is the code snippet along with a link to view it online: Check out the demo here

<style>
        * {
            box-sizing: border-box;
            font-family: sans-serif;
        }
        h1, 
        h2{
            margin-left:10px;
        }
        /* Styles omitted for brevity */
    </style>

<body>
   <!-- Code snippet to showcase the issue goes here -->
</body>

<script>
    // JavaScript logic for handling the functionality
</script>

Hello everyone, I received great assistance from Aaron earlier regarding my project. However, I stumbled upon another challenge while developing the light-box feature for the app. When clicking on the 'VIEW' button, the overlay displays only the first image in the collection regardless of which image was clicked. This seems to be another problem related to the ng-repeat function. Each object contains the main image URL at x.mainImage.url, which should be accessed through the ng-repeat loop with x.mainImage.url. Unfortunately, the implementation isn't working as intended. Any suggestions or guidance on how to fix this issue would be immensely helpful. Here's the relevant code snippet below and you can also check it out online: View the demo here

<style>
    * {
        box-sizing: border-box;
        font-family: sans-serif;
    }
    h1, 
    h2{
        margin-left:10px;
    }
    /* Additional styles are included */
  </style>

 <body>
<!-- Revised code block showcasing the issue -->
 </body>

  <script>
    // Custom JavaScript functions to control the light-box behavior.
  </script>

Answer №1

While you inquired about implementing this the Angular way, it's essential to note that ng-mouseenter and ng-mouseleave come with high performance costs. In a real-world application, it is recommended to handle these interactions using CSS.

Let me demonstrate how to resolve the issues in your approach and provide you with a more efficient CSS solution :)

In this scenario, the $index variable proves to be valuable as it can be utilized within an angular template under an ng-repeat tag to capture the index of the current data item being looped through. You should utilize this variable to store the index of the currently hovered item in the controller scope. Subsequently, when the mouse moves away from the item, you can discard the stored index.

When applying styles, leverage a ternary operator to assign active or inactive styles based on whether the item's index matches the saved active index variable on the scope.

In case you are unfamiliar, a ternary expression serves as a concise form of a conditional statement i.e.,

conditional_expression ? value_returned_if_true : value_returned_if_false
. It offers a succinct means of crafting conditional statements in javascript (or an angular template which interprets javascript in this instance).

For this demonstration, I combine a ternary expression with saving the index of the last item entered by the mouse to allocate hover or non-hovered styles to each item.

This is an abbreviated version mimicking your example:

Angular controller:

app.controller('exampleController', function($scope) {
  $scope.overlayColorStyles = { "opacity": 0 };
  $scope.overlayTextStyles = { "opacity": 0 };
  $scope.overlayTextStylesActive = { "opacity": 1 };
  $scope.overlayColorStylesActive = { "opacity": .75 };
  $scope.activeItemIndex = null;
});

Template:

<div id="outer" class="outer">
  <div class="inner"
      ng-mouseenter="$scope.activeItemIndex = $index"
      ng-mouseleave="$scope.activeItemIndex = null"
      ng-repeat="x in insideData">
      <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
      <div ng-if="x.service=='Twitter'&& x.mediaType!='image'" class="outer-caption"><div class="inner-caption">{{x.caption}}</div></div>
      <div class="overlay-color"
        ng-style="$scope.activeItemIndex === $index ? overlayColorStylesActive : overlayColorStyles">
      </div>
      <div class="overlay-text"
        ng-style="$scope.activeItemIndex === $index ? overlayTextStylesActive : overlayTextStyles">
        VIEW
      </div>
  </div>
</div>

It should be noted that this code should mainly serve as a learning exercise. Angular's primary role does not involve styling based on user interactions. Attempting to do so may significantly slow down your application, especially with an increasing number of items. Utilizing CSS for this purpose will result in notably better performance :)

CSS alternative below:

html:

<div id="outer" class="outer">
  <div class="inner"
      ng-repeat="x in insideData">
      <img ng-if="x.service=='Instagram'||(x.service=='Twitter' && x.mediaType=='image')" ng-src='{{x.thumbnails[0].url}}'>
      <div ng-if="x.service=='Twitter'&& x.mediaType!='image'" class="outer-caption"><div class="inner-caption">{{x.caption}}</div></div>
      <div class="overlay-color"></div>
      <div class="overlay-text">VIEW</div>
  </div>
</div>

CSS:

.overlay-color {
  opacity: 0.0;
}

.overlay-text {
  opacity: 0.0;
}

.inner:hover .overlay-text {
  opacity: 1.0;
}

.inner:hover .overlay-color {
  opacity: 0.75;
}

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

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...

Using jQuery to align a div element to the top of the viewport

Is there a way to keep the #lightbox div positioned at the top of the viewport consistently? $(document).ready(function(){ $('.mehr').click(function() { $("body").css("overflow", "hidden"); $('#lightbox').css({'visibil ...

Is it possible to incorporate an editable text feature within react-moveable? (Allowing for both dragging and editing capabilities)

In React Movable box, the text can be dragged with a left click and edited with a right click using the "contentEditable" attribute. However, on smartphones, editing seems to be disabled and only dragging is possible. <div className="move ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

How can one update transitive dependencies to a specific newer version in npm to address CVE vulnerabilities?

Here are the packages that require upgrading. I attempted to update the version and signature of the packages listed in package-lock.json. However, whenever I run npm i after modifying package-lock.json, the changes made to package-lock.json disappear. ...

Guide to iterating through an object and generating child components in React.js

Struggling with a React.js loop through child component issue as a newcomer to the language. I have an object and want to create child components from its values. Any help would be greatly appreciated. var o = { playerA: { name: 'a', ...

Unable to access the `Modal` through the Header link using the shared service

I have developed a service specifically for modal functionality. It is functioning perfectly when triggered by a button within the body of the page, but it fails to work when called from the header section. The service is included in both scenarios. To b ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Angular JS modal displaying CKEditor is not functioning properly

Utilizing AngularJS, I have implemented a CK editor within a uibmodal window. <div> <textarea ckeditor="editorOptions" id="ckID" ng-model="content"></textarea> </div> To insert text into the CK Editor upon clicking a button name ...

Guide on how to pass the chosen dropdown value from a custom component back to the main component

I've developed a customized MUI select component in React and have integrated it multiple times within another component as shown: customDropdown.js import * as React from 'react'; import FormControl from '@mui/material/FormControl&ap ...

Do identical files stored in separate locations produce unique sha1 hashes?

var crypto = require('crypto'); var fs = require('fs'); var file1 = process.argv[2]; var file2 = process.argv[3]; var sha1sum = function(input){ return crypto.createHash('sha1').update(JSON.stringify(input)).digest(' ...

Obtaining the current domain within an Angular model (specifically an Angular service housing ajax calls) in order to construct the complete API URL for fetching data

When deploying our application, we ensure that it works flawlessly on both demo and live sites. The demo URL will be structured as demo.xxxx.com and the live URL will simply be xxxx.com. Within the angular service layer, I am utilizing asp.net webapi meth ...

Comparing AJAX to a source script request

As I was exploring the Google API today, I came across their sample code where they simply request a URL using: <script src="src="https://www.googleapis.com/customsearch/v1?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1.."></script> Before seeing this, I ha ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...

Is anyone utilizing PHP variables to control the title of the HTML and the ID of the body element?

I utilize PHP variables to store the title's value and the ID of the body. The latter is a method to show which section of the page the user is currently on (in this case, the "home" section). At the start of my index.php: <?php $title = "New ...

What is the best way to exclude certain values from Objects in Javascript?

Imagine having an object structured like this: "errors": { "name": { "name": "ValidatorError", "message": "Minimum length 6 characters.", "propert ...

React - using dangerouslySetInnerHTML does not display the expected output

When I enter the following text in the textbox labeled "Type Here" AAA: <HEllo> BBB: <HE llo> The desired result should be identical to what is entered in the "Type Here" box. However, the actual result box does not display the same output ...