Using Angular directive with ng-class to display or hide element

I am trying to implement a feature in my directive template where an element is shown or hidden on mouseenter. Below is the code for my directive:

angular.module('myApp')
.directive("addToRoutes",['$http', '$timeout', function($http, $timeout) { 
    return {
        template: '<div><a class="btn btn-default btn-round" ng-click="copy()" ng-mouseenter="showText()" ng-mouseleave="hideText()">\
            <span class="icon icon-spinner icon-spin hidden" ng-class="{hidden : !loading}"></span>\
            <span class="icon icon-plus"   ng-class="{hidden : (loading || copied)}"></span>\
            <span class="icon icon-check hidden" ng-class="{hidden : !copied}"></span>\
            <span class="hidden" ng-class="{hidden : !showFull}">Nach mein Routen Kopieren</span></a></div>\
        ',
        replace: true,
        restrict: 'AE',
        scope: {},
        link: function($scope, element, attrs) {   
            var routeId = attrs.route;
            $scope.loading = false;
            $scope.copied = false;
            $scope.showFull = true;

            $scope.showText = function(){
                $scope.showFull = true;
            }

            $scope.hideText = function(){
                $scope.showFull = false;
            }

            $scope.copy = function(){

            }

        }
    }
}])

The issue I am facing is that the showing/hiding functionality only works on the second iteration, meaning I have to enter, leave and then re-enter for it to work properly. I suspect it has something to do with the scope variables.

Any suggestions on how to fix this?

Answer №1

make sure to initialize the $scope.showFull variable to false for it to work properly from the start

check out this example: http://plnkr.co/edit/g5gWfSOrQDaNbYDQPgyS?p=preview

.directive("addToRoutes", function($http, $timeout) {
  return {
    template: '<div><a class="btn btn-default btn-round" ng-click="copy()" ng-mouseenter="showText()" ng-mouseleave="hideText()">\
            <span class="icon icon-spinner icon-spin hidden" ng-class="{hidden : !loading}"></span>\
            <span class="icon icon-plus"   ng-class="{hidden : (loading || copied)}"></span>\
            <span class="icon icon-check hidden" ng-class="{hidden : !copied}"></span>\
            <span class="hidden" ng-class="{hidden : !showFull}">Nach mein Routen Kopieren</span></a></div>\
        ',
    replace: true,
    restrict: 'AE',
    scope: {},
    link: function($scope, element, attrs) {
      var routeId = attrs.route;
      $scope.loading = false;
      $scope.copied = false;
      $scope.showFull = false;

      $scope.showText = function() {
        $scope.showFull = true;
      }

      $scope.hideText = function() {
        $scope.showFull = false;
      }

      $scope.copy = function() {

      }

    }
  }
});

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

Anticipating the fulfillment of promises with the power of Promises.all

I have adopted the code found here for loading multiple .csv files. Upon successful loading of these files, my intention is to then render a react component. Below is the method located in datareader.js that I am currently working with. I am exploring the ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Finding the Biggest Number in an Array

I've come up with a solution using Math.max(), but I'm curious why the following approach isn't working. array = [4, 5, 1, 3] for (var i = 0; i < array.length; i++) { var num = 0; if (array[i] > num) { num = array[i]; } } ...

"Tricks to prompt the browser to refresh and load up-to-date content

Currently experiencing issues with my web browser (both on my laptop and smartphone). I am working on a website page (HTML, javascript) and have observed that my browser keeps retrieving cached information instead of loading the page each time, preventing ...

Using Javascript within an HTML document may not provide the intended functionality

My script: <!DOCTYPE html> <html> <head> <script> $(document).ready(function () { document.getElementById("saveForm").click(); }); </script> </head> <!--<body onload="document.getElementById('saveForm&apos ...

Efficiency in Javascript coding techniques

Hey there, I'm seeking some feedback on the efficiency of my aspect ratio function. This function is designed to determine the aspect ratio and limit the size of an image. Take a look and let me know what you think! function constrainTwoNumbers(optio ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

Having trouble making the state.go function to function properly

Struggling to make this code snippet work: scope.takeTest = function (assessment) { console.log(assessment._id); state.go('app.tab.assessments', { id: assessment._id }); console.log('hi'); }; The logs a ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

Building an Ionic app from a .git repository on your local machine: A step-by-step guide

Trying to set up Moodle's ionic mobile app on my local machine using Windows and following these steps: cd project-directory ionic platform add android Encountered an error in the command prompt: throw err; ^ Error: Cannot find module ' ...

halt execution of npm test and erase any printed content

When I run npm test on my React project, it runs unit tests using jest and react testing library. The test logs (including console log lines added for debugging) are printed to the screen but get deleted after running the tests. It seems like the logs are ...

What is the process through which React form elements receive the event parameter?

I'm currently working on a form component that looks like this: import React from 'react'; class CommentBox extends React.Component { constructor(props) { super(props); this.state = { value: '' } this.han ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...

What is the best way to display JavaScript in a view in ASP.NET MVC 3?

Good day Everyone, I am currently facing an issue with a javascript variable in my view. This is what I have been trying to do... var skinData = null; and then, when the document is ready.... $.ajax({ type: 'POST', ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Jest - Test snapshot failure occurred following the inclusion of "</React.Fragment>"

I encountered an error message while running Jest. As I am not very familiar with using Jest, I would appreciate any insights on why this test is failing. Results: Jest test result: - Snapshot + Received - <span - className="icon icon-dismiss size-2 ...

The PDF structure in vue3-pdf is not valid and may cause errors

This error is occurring on almost every file, except for one that works fine. The console also displays the following warning: Warning: Indexing all PDF objects. Object { message: "Invalid PDF structure.", name: "InvalidPDFException", ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Packager freezing after running npm audit and the component directory is nonfunctional

Greetings, To begin with, I would like to acknowledge that this issue may have been addressed in previous posts, but despite following suggestions on Stack Overflow and GitHub, I am still facing two specific problems. Here are the issues I am encounterin ...

Distinct elements within a JavaScript hash

Is there a jQuery method to add a hash into an array only if it is not already present? var someArray = [ {field_1 : "someValue_1", field_2 : "someValue_2"}, {field_1 : "someValue_3", field_2 : "someValue_4"}, {field_1 : "someValue ...