How to display unique content within a div based on individual element hover using AngularJS

As a newcomer to AngularJS, I am facing some challenges while working with directives.

Currently, I am working on a navigation menu where my goal is to dynamically display different information within the .services-content section upon hovering over each li element in the .services menu. Additionally, I have successfully implemented a background color change effect based on the hovered item, but I am struggling with displaying custom content for each item.

This is how my HTML looks:

<div class="page-navigation row">
<div class="col-sm-4">
    <!-- Some content here -->
</div>
<div class="col-sm-4">
    <h6>Navigation</h6>
    <nav>
        <ul class="list-unstyled nav-list">
            <!-- Here is my directive  -->
            <li class="services" showcontentonhover>
                <ul class="list-unstyled">
                    <li>
                        <a href="fi.html">Go to Fi</a>
                    </li>
                    <li>
                        <a href="fa.html">Go to Fa</a>
                    </li>
                    <li>
                        <a href="fo.html">Go to Fo</a>
                    </li>
                </ul>
            </li>
            <li>
               <!-- some other link -->
            </li>
            <li>
               <!-- some other link -->
            </li>
            <li>
               <!-- some other link -->
            </li>
        </ul>
    </nav>
</div>
<div class="col-sm-4 services-content">
    <!-- Desired content should be displayed here! -->
    <p>Each li in .services should have a corresponding paragraph here</p>
    <a href="foo">This anchor item should link to the same URL as the hovered element</a>
</div>

Below is my directive:

app.directive('showcontentonhover',
function() {
    return {
        restrict: 'A',
        link : function($scope, element, attrs) {
            var el = element.find('li');

            el.bind('mouseenter', function() {
                $(this).siblings().removeClass('active-nav');
                $(this).addClass('active-nav');
            });

            el.eq(0).bind('mouseenter', function() {
                $('.services-content').css('background-color', '#14202B' );
                // Need to modify the content of .services-content here
            });
            el.eq(1).bind('mouseenter', function() {
                $('.services-content').css('background-color', '#1858a5' );
                // Need to modify the content of .services-content here
            });
            el.eq(2).bind('mouseenter', function() {
                $('.services-content').css('background-color', '#2196F3' );
                // Need to modify the content of .services-content here
            });
        }
    }
});

After my research, I believe that creating a directive template or utilizing transclude might solve this issue, but I'm still unsure. The AngularJS version I am using is 1.5.3.

Any help would be greatly appreciated. Thank you!

Answer №1

Utilize the scope and = (two-way data-bindings) in conjunction with a directive.

Here is a practical example:

var app = angular.module('app',[])
    .directive('showcontentonhover',function() {
        return {
            restrict: 'A',
            scope:{
                contentModel:'='
            },
            link : function($scope, element, attrs) {
                var el = element.find('li');

                el.bind('mouseenter', function() {
                    $(this).siblings().removeClass('active-nav');
                    $(this).addClass('active-nav');
                });

                var data = [
                    {
                        bg:'#14202B',
                        content:'content changed ....'
                    },
                    {
                        bg:'#1858a5',
                        content:'Another content value....'
                    },
                    {
                        bg:'#2196F3',
                        content:'Yet another content....'
                    }
                ];

                angular.forEach(el,function(val,index){
                    angular.element(val).bind('mouseenter', function() {
                        $('.services-content').css('background-color', data[index].bg );
                        $scope.$apply(function(){
                            $scope.contentModel.text = data[index].content;
                        });
                    });
                });
            }
        }
    });
<html ng-app='app'>
<head>
    <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="//cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/angular.js/1.5.3/angular.js"></script>
</head>
<body>
    <div class="page-navigation row" ng-init=" contentModel={text:''} ">
        <div class="col-sm-4">
            <!-- Some content here -->
        </div>
        <div class="col-sm-4">
            <h6>Navigation</h6>
            <nav>
                <ul class="list-unstyled nav-list">
                    <!-- Here is my directive  -->
                    <li class="services" showcontentonhover content-model="contentModel">
                        <ul class="list-unstyled">
                            <li>
                                <a href="fi.html">Go to Fi</a>
                            </li>
                            <li>
                                <a href="fa.html">Go to Fa</a>
                            </li>
                            <li>
                                <a href="fo.html">Go to Fo</a>
                            </li>
                        </ul>
                    </li>
                    <li>
                        <!-- some other link -->
                    </li>
                    <li>
                        <!-- some other link -->
                    </li>
                    <li>
                        <!-- some other link -->
                    </li>
                </ul>
            </nav>
        </div>
        <div class="col-sm-4 services-content">
            <!-- I want my content to be here! -->
            <div ng-bind="contentModel.text"></div>
            <p>Different paragraph for each li in .services</p>
            <a href="foo">This anchor item should have the same href that the hovered element</a>
        </div>
    </div>
</body>
</html>

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

Enhancing HTML Documents with the Header Element

When HTML 5 was implemented, it brought along new semantic tags such as header and footer. I find myself puzzled on whether I should use the header tag directly or assign a class of "header". Which option is superior and why? ...

Issue with image not fully encompassing div in Bootstrap 5

Currently working on a grid layout with images within the Bootstrap 5 framework. Here is the code snippet for the grid: #project_images img { height: 100%; width: 100%; object-fit: cover; } <section> <div class="container" id ...

What are some techniques for aligning div elements with varying heights?

I have been attempting to align div elements like in this example: https://i.sstatic.net/FoBPg.png However, my result is not turning out as expected: https://codepen.io/online123/pen/VwvGoQP The HTML code I am using is: <div class="under d-flex fle ...

Discovering the specific element that was clicked from a collection of elements

I'm dealing with a scenario where multiple divs share the same class. There is a dropdown that alters the background color of one of these divs when a certain option is selected (for example, option 2 changes div #2's background color). My dile ...

Modify the CSS color attribute interactively by clicking

I have a function that can generate random colors. I would like to utilize this function along with jQuery's toggleClass feature to change the color of a table cell when clicked, and revert it back to its original color if clicked again. Here is the ...

Issue with non-callback pattern in AngularJS $resource functionality prevents it from working as

After reading the document on the angularjs website, I discovered a way to manipulate my factory like this: var speicialProducts = []; factory.getFeatureProducts = function () { if ($.isEmptyObject(specialProducts)) { specialProducts = $res ...

Contrasts in padding arrangements between Firefox and other browsers

Take a look at the following code snippet: https://jsfiddle.net/a13nd32u/3/ #post_part{display:inline;padding:6px 9px;float:right;font-size:15px} select{width:80px;height:21px;padding-right:10px;display:inline} #button1{display:inline;padding-left:10px} ...

Optimizing performance with ng-if for 500 watchers

When repeating data with ng repeat, I encountered an issue where some of the data.image (src) values were null and I did not want them to be included in the repeat process. To solve this issue, I implemented a simple ng-if statement. <div ng-repeat="d ...

AngularJS retrieves entire video file for HTML5 video tag

I am currently developing a web application with AngularJS where the main page showcases five videos for the user to choose from and play. However, I have encountered an issue where all source video files are being downloaded for each HTML5 video element d ...

Restrict certain sections of the website to authorized users only

In my game project, players are presented with two options: to play the game itself or to view global and local highscores. I have implemented a signup and login system where upon successful login, users can choose among playing the game, checking highscor ...

Executing script once the DOM has completed loading

In my project, I'm dynamically generating menu items for a menu bar based on headers from external files that are imported using an XMLHttpRequest(). The menu bar is then updated as I navigate through different pages. Everything works smoothly. Each ...

Adaptable Bootstrap navigation bar

In the process of creating a responsive menu, I have designed a navbar for desktop that includes 3 text links and 3 small pictures that are also links. However, when transitioning to a smaller screen size, my goal is to keep the 3 small pictures as they a ...

Searching for specific expressions within HTML files on Windows can be accomplished using the grep or findstr commands, allowing you to display the

I am trying to use grep or findstr to extract the correct IMDB number when searching for a specific movie by its title. For example, the movie "Das Boot" is listed on IMDB with the movie number tt0082096. Currently, I am attempting to search through HTML ...

Displaying a Bootstrap card with ellipsis text-overflow following a short excerpt of text

When working on a web application using the Bootstrap library, I utilized card classes. The goal was to truncate text that was too long, as shown in the image below: https://i.sstatic.net/4wKyT.jpg However, the result I achieved looked different than exp ...

Exploring BreakPoints using gridlisttiles

Can Grid List Tile components be configured to occupy the entire screen on small devices using sm={12} lg={6}, but only half of the screen on larger devices? If not, is there a way to adjust the grid list layout to display fewer tiles per row on smaller ...

JavaScript can sometimes present peculiar challenges when it comes to setting style attributes, especially when a DOCTYPE is

It seems like I am encountering an issue when trying to dynamically create and modify a <div> element using JavaScript. The problem arises when I use the XHTML 1 Transitional doctype. This is how I am generating the <div>: var newDiv = docume ...

Ways to conceal the player controls with mediaelementjs.com

Is there a way to display the control bar only when the user hovers over the video while using the mediaelementjs.com player? I feel like there might already be a function for this, but I can't seem to find it anywhere. Should I just implement a simpl ...

Using Geolocation in HTML5 and JavaScript

Currently, I am working on my debut mobile web application and have successfully integrated Google Maps into it using Geolocation JavaScript API version 3. Now, I am looking to add a button that, when clicked by the user, centers the map on my location o ...

Troubleshoot: Unable to send or receive messages in Socket.IO Chat

I recently tried following a tutorial on socket.io chat, which can be found here. Although the tutorial video showed everything working perfectly, I have encountered issues with my implementation. It seems like the messages are not being sent or received ...

How can I redirect to another page when an item is clicked in AngularJS?

Here is an example of HTML code: <div class="item" data-url="link"></div> <div class="item" data-url="link"></div> <div class="item" data-url="link"></div> In jQuery, I can do the following: $('.item').click ...