How to toggle a div's visibility in AngularJS with a click事件

I am developing a filter that requires me to create 3 popups using the ng-repeat directive in Angular. Each popup should have the same class name but a different id. When a button is clicked, I want one popup to show while the rest hide.

I currently have a working code using a single scope variable, but I'm wondering if there is a better way to achieve this. In jQuery, it only takes 2 lines of code to accomplish this, but I'm unsure of the most efficient method in Angular.

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

    $scope.IsVisible = [false];

    $scope.mainList = [];
    var obj = {};
    obj.name = "swimlanes";
    obj.list = [];
    $scope.mainList.push(obj);
    obj = {};
    obj.name = "programs";
    obj.list = [];
    $scope.mainList.push(obj);
    obj = {};
    obj.name = "programs";
    obj.list = [];
    $scope.mainList.push(obj);


    //click event of rect trangle
    $scope.click = function(key, index) {
        var flag = $scope.IsVisible[index];
        $scope.IsVisible = [false];
        $scope.IsVisible[index] = !flag;
        $scope.myObj = {
            "top": key.currentTarget.offsetTop + "px",
            "left": key.currentTarget.clientWidth + 10 + "px"
        }
    }
});




   <div  ng-repeat="val in mainList" id={{val.name}} class="mainPopup" ng-show="IsVisible[$index]" ng-style="myObj">

The current code works well, but I am seeking a more optimal approach. If you have any suggestions or improvements, please let me know.

Here is the working code.

Answer №1

To enhance the controller, consider replacing the $scope.IsVisible with a variable that directly references the selected item in mainList. This way, there is no need to manage an array of booleans.

$scope.selected = null;

Modify $scope.click as follows:

$scope.click = function(key, index) {
    $scope.selected = $scope.mainList[index];
    $scope.myObj = {
        "top": key.currentTarget.offsetTop + "px",
        "left": key.currentTarget.clientWidth + 10 + "px"
    }
};

Furthermore, ensure to update your HTML to utilize $scope.selected for controlling the visibility of the details:

<div  ng-repeat="val in mainList" id={{val.name}} class="mainPopup" ng-show="val == selected" ng-style="myObj"></div>

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

Unable to locate $element post minification

I've encountered a peculiar bug that only seems to manifest when my web application is running in Karaf, but not on the webpack-dev-server. Whenever I open a dialog while the web app is running in Karaf, I receive this error in the browser console: a ...

Utilizing JavaScript to retrieve data using AJAX

Having trouble sending emails through ajax on my website. The form is in a modal (using custombox), but all values being sent are null. How can I utilize getElementById in modal content? Link to custombox git's hub: https://github.com/dixso/custombox ...

Is there a way to utilize an AXIOS GET response from one component in a different component?

I'm having trouble getting my answer from App.tsx, as I keep getting an error saying data.map is not a function. Can anyone offer some assistance? App.tsx import React, {useState} from 'react'; import axios from "axios"; import {g ...

Using Angular to convert JSON data to PDF format and send it to the printer

Currently, I am retrieving JSON data from an API and now need to convert this data into a PDF format for printing. I am encountering an issue where the CSS styling for page breaks is not rendering properly within my Angular component. When I test the same ...

Tips for implementing server-side pagination with Angular-UI Bootstrap by utilizing the skip parameter

i have a number of items generated using ng-repeat, i have to implement pagination.but everywhere i can see by getting the count value of items, i can add. but i am struggling with implementing skip functionality. For example, if the skip value is set to 1 ...

Angular - Utilizing a Directive Controller to access the $attrs value as an object

As a beginner in Angular (just 3 days in), I've created the following view: <div ng-repeat="keyword in vc.promotionData.keywords"> <keyword data="keyword"></keyword> </div> The directive for my keyword looks lik ...

Replicate elements along with their events using jQuery

Every time I utilize ajax to dynamically generate new content using methods like .clone(), append(), etc., the newly created element loses all triggers and events that were programmed =( Once a copy is made, basic functionalities that work perfectly on ot ...

Learn the technique for showcasing numerous markers on Google Maps, each equipped with its own individualized info windows

https://i.sstatic.net/1tTUD.png // map center var center = new google.maps.LatLng(2.855262784366583, 105.4302978515625); function initialize() { var mapOptions = { center: center, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Create a < ...

How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected. Here is my Vue app: https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue I expected the selected color to match the color in the ...

Elevate the functionality of your table in BoostrapVue by customizing it to display items

How can I modify the code below to turn the items into input fields that the user must enter? Instead of listing the items, I would like to replace them with input fields. <template> <div> <b-form-input v-for="(item, index) in items" ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Discovering terms in JavaScript

Looking at a sorted array like this: var arr = [ "aasd","march","mazz" ,"xav" ]; If I'm searching for the first occurrence of a letter that starts with "m", how can I achieve it without iterating through the entire array? ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...

Stop images from being stored in the database instead of text characters

Using a proxy, I attempt to parse some HTML. One of the elements is retrieved using jQuery: var site = 'http://www.kartabu.com/pl/index.php?filter=random' var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeUR ...

What is the best way to ensure that the drop shadow on the bootstrap carousel is not confined by the parent element?

I'm currently using bootstrap's carousel to display items, and I've noticed that the box-shadow attribute on my item blocks is being limited by the parent element that wraps it. https://i.sstatic.net/ks5lC.png Is there a way for me to ensu ...

What causes req.body to display as an empty object in the console during a POST request?

Having some trouble with my code. The middleware is supposed to return parsed data in the console as an object accessed by req.body, but it keeps returning an empty object for some reason. Check out Code and Console Snapshot 1 View Code and Console Snapsh ...

The variable you have attempted to access has not been assigned

Querying mongo through mongoose with customer.find() returns the following data: [{ _id: 5029a09e099fb5095fdb2d73, clientId: 22, company: 'X', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97cfd7 ...

Is there a proper method for creating a "dark" theme in Angular Material?

Struggling to create a theme with dark indigo background and white font using Angular Material themes. While CSS can achieve this, I assumed there would be an easier way through theming. Can someone guide me on how to make the font white in my configuratio ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

The var_dump($_POST) function is not displaying any results after submitting the form to the CodeIgniter controller

Can someone assist with my jQuery code? $(document).on("click", ".addthisone", function (e) { var file_data = $(this).parent().parent().parent().find('input[type=file]').prop("files")[0]; console.log(file_data); var form_data = new F ...