Display and conceal directive individually - AngularJS

I've been working on creating a tooltip for my directive, but I'm facing an issue where all four tooltips appear or none at all when clicking on the green div. Can anyone help me figure out what I'm doing wrong?

Check out the Working Plnkr - here

HTML -

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>    
    <script src="script.js"></script>
</head>
<body ng-controller="mainCtrl"> 
    <div class="con-div" ng-repeat="row in fakeDataSet" ng-click="data.clicked = !data.clicked">
        <test-div click-val="data.clicked"></test-div>
    </div>
</body>
</html>

JavaScript -

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

myApp.controller('mainCtrl', function($scope){

    $scope.fakeDataSet = [1,2,3,4];
    $scope.data = {};
    $scope.data.clicked =  false;
});

myApp.directive('testDiv', function(){
    return {
        restrict: 'EA',
        scope: {
            clickVal: "="
        },
        link: function (scope, element, attrs){
            console.log("clickVal", scope.clickVal);
        },
        template: '<div class="tooltip" ng-if="clickVal">This is a tooltip</div>'
    };  
})

Answer №1

To ensure that each instance of the directive has its own scope, you can modify your code like this. By binding the click event to a function that resets all truthy/falsy values before setting the active one, only one instance will remain open.

<div class="con-div" ng-repeat="row in fakeDataSet" ng-click="setToolTip(row)">
    <test-div click-val="data.clicked[row]"></test-div>
</div>

$scope.fakeDataSet = [1,2,3,4];
$scope.data = {};
$scope.data.clicked =  {1: false, 2: false, 3: false, 4:false};

$scope.setToolTip = function(row){
    Object.keys($scope.data.clicked).forEach(function(elem){
        $scope.data.clicked[elem] = false;      
    });
    $scope.data.clicked[row] = true;
}

Answer №3

It appears that the same click value has been bound to all elements, causing all tooltips to appear or disappear simultaneously.

<div class="container" ng-repeat="item in dataItems" ng-click="item.clicked = !item.clicked">
    <tooltip-item click-value="item.clicked"></tooltip-item>
</div>

$scope.dataItems = [{value : 1, clicked : false},
{value : 2, clicked : false},
{value : 3, clicked : false},
{value : 4, clicked : false}];

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

Steps for creating an animation for a "v-for" element using a "v-if" statement in Vue

I attempted to create an animation, but it's not working as expected. I also experimented with using transition-group. How can I modify this code to make it functional? The goal is to display two different lists based on the category of data retrieve ...

What is the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

Steps to avoid TypeError: e.target.getAttribute is not a function

My goal is to make the inner code (result) function only when a Validity attribute is present. However, my target lacks said attribute, so I'm looking for a way to use an if statement to prevent the inner code from executing. How can I avoid the Type ...

Issue with Windows screen resolution affecting CSS dimensions

Encountering a strange issue – on Windows 10, some laptops have the default screen setting at 125%, making web pages appear too big since they were designed for 100% scale. Any suggestions on how to address this? CSS? JavaScript? I'm unsure of the ...

Error: Rejection was not properly handled, despite successful test results

I have implemented a function to test: UserController.prototype.getDashboard = function getDashboard(req, res, next) { let pages, user; return this.User.findById(req.user.id) .populate('club') .execAsync() .then(dbUser => { ...

Is there a way to verify if a Backbone.View is actively displayed in the DOM?

Is there a way to determine if a Backbone.View is currently rendered in the DOM, so that I do not need to rerender it? Any suggestions on how this can be achieved? Thanks and regards ...

Is there a way to create a glow effect in CSS that considers the background color?

Exploring ways to create realistic-looking LEDs using HTML and CSS has been a fun challenge. Achieving a glowing effect for each LED would be simple if the color remained constant. However, I aim for the glow to dynamically adjust based on the LED's c ...

Show just a trio of pagination figures from the overall collection in Javascript

I have been working on implementing pagination numbers in JavaScript. While I have managed to achieve pagination and display all the numbers, I am looking to show only three numbers out of all the available numbers. Here's what I have accomplished so ...

The model.find() method of Mongoose results in an empty array being returned

I've created a MongoDB database named entertainment, with a collection called medias. This collection contains JSON data. When I make a call to the database using Postman: http://localhost:8000/data, it returns an empty array. Below is my complete c ...

Implementing user authentication in Rails with Devise and Backbone framework

I am just getting started with backbone.js. Currently, I am working on a rails application utilizing the "backbone-on-rails" gem. After successfully incorporating 3 models and rendering views with backbone, now I am looking to implement authentication usin ...

Updating the "onclick" event for a button input doesn't function properly in Internet Explorer versions 8 and 9 and Firefox when using jQuery due to their lack of recognition for the change

<input id="UploadButton" type="button" value="Upload" onclick="xyz"/> <script language="javascript" type="text/javascript"> $(function () { $().SPServices({ operation: "GetList", listName: "Docs", ...

"Implement a feature that allows for infinite scrolling triggered by the height of

Looking for a unique solution to implement a load more or infinite scroll button that adjusts based on the height of a div. Imagine having a div with a height of 500px and content inside totaling 1000px. How can we display only the initial 500px of the div ...

Discovering iBeacon using Web Bluetooth

I've been experimenting with the new web bluetooth feature, using one of these estimote beacons: Having identified the uuid for my beacon, here is the angular app code I'm currently utilizing (with references to $scope and $window): $scope.runB ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

Leveraging previous state values within a setInterval function in React

Could someone please provide me with an answer to this topic? When I attempt to implement the Interval in the correct way (including cleanup), I encounter the following code: const [count,setCount] = useState(0) useEffect(() => { const interval = ...

What approach provides the most effective way to navigate through an NPM Package?

I have an idea to enhance a particular open source NPM package. Although I understand the necessary steps, it would be incredibly beneficial to have the ability to debug the package while it is in operation. Is this achievable? ...

Struggling to correctly showcase my Firebase data in Angular using the orderByChild method

I have a user database structured like this : Database - Users - Id (generated using the push method) - email - firstName - ptsTotal - ... I am looking to create a ranking of users based on their total points (ptsTotal) in a game using ...

Searching for a deeply nested JSON property with lodash

I am dealing with a JSON API response that has the following structure: [ { title: "top1", sections: [ { section_title: "section1", content: [ { content_title: "title1", content_id: "id1" ...

Issue with rendering Rails View using Javascript

In my show.html file, I have an <a ng-click="writeReview(product)" class="vote-link">Review</a> link. Within my javascript file, I have the following code: $scope.writeReview =(product) -> $http.get("/products/#{product.id}/review/new" ...

A guide on using JavaScript with Selenium to continuously refresh a page until a specific element disappears

When working with selenium in JavaScript, I have a challenge where I need to constantly refresh the page until a specific element disappears. The issue arises because selenium uses promises, and using a for loop creates multiple promises even when the cond ...