How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same button again will close it up. If a second button is clicked, it should collapse the content for that button while closing the content from the first button. Essentially, I want it to function like a collapsible panel in Bootstrap but built solely with Angular. I have made some progress so far, but as I am new to Angular, any help would be greatly appreciated...

Here is a link to the fiddle:

<body ng-app="app">
  <div ng-controller="Test" class="container">
  <div class="custom">
    <button ng-click="show = 1" class="btn">Collapse 1</button>
    <button ng-click="show = 2" class="btn">Collapse 2</button>
      <div class="form-group" ng-show="show==1">
        <div class="sec">Showing content for Collapse 1</div>
    </div>
    <div class="form-group" ng-show="show==2">
      <div class="sec">Showing content for Collapse 2</div>
    </div>
    <div class="form-group" ng-show="show==3">
    </div>
  </div>
  </div>
</body>

Answer №1

If you're looking for a solution that meets your requirements, check out this updated fiddle. It's been modified to work without bootstrap but with ng-animate for animations.

In the updated code, I've wrapped your form-group elements in a wrapper and switched from using ng-show to ng-if.

//html
<button ng-click="showDiv(1)" class="btn">collapse 1</button>
<button ng-click="showDiv(2)" class="btn">Collapse 2</button>

<div class="sec-wrp" ng-if="show === 1">
    <div class="form-group" >
      <div class="sec">show 1</div>
    </div>
</div>

 <div class="sec-wrp" ng-if="show === 2">
    <div class="form-group" >
      <div class="sec">show 2</div>
    </div>
</div>

<div class="form-group" ng-if="show==3" >
</div>

The click event now triggers a function in your controller based on the selected div to show. The controller responds by updating the $scope.show value accordingly. If the passed value matches the currentShow value, it toggles the visibility of the div.

//controller
var app = angular.module('app', ['ngAnimate']);
app.controller('Test', ['$timeout','$scope', function($timeout, $scope) {
    $scope.show = 0;
    var currentShow = 0;

    $scope.showDiv = function(int){
        $scope.show = 0;

        if(currentShow === 0){
           currentShow = int;
           $scope.show = int;
           return false;
        }

        if(currentShow === int){
           $timeout(function(){
               currentShow = 0;
               return false;
           }, 1000)
        }else{
           $timeout(function(){
               currentShow = int;
               $scope.show = int;
           }, 1000)
        }
    }

}]);

The timings in the code correspond to the transition durations in your CSS animations (ng-enter, ng-leave). Adjust the timeouts if you modify the transitions.

//css
.custom{position: relative; z-index: 2; border: 1px solid #ccc;}
.sec{
  padding: 20px;
  border: 1px solid orangered;
  background: orange;
  height: 100px;
  z-index: 1;
}

.sec-wrp{
  overflow: hidden;
  transition: all ease 1s;
}

.sec-wrp.ng-enter{
  opacity: 0;
  height: 0;
}

.sec-wrp.ng-enter.ng-enter-active{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave.ng-leave-active{
  opacity: 0;
  height: 0;
}

I hope this solution is helpful for you.

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

How can jQuery retrieve a string from a URL?

If I have a URL like http://www.mysite.com/index.php?=332, can jQuery be used to extract the string after ?=? I've searched on Google but only found information about Ajax and URL variables that hasn't been helpful. if (url.indexOf("?=") > 0) ...

In this guide, learn the best way to dynamically adjust image height to match the height of any device

I am trying to make sure that the image on the front page of my website fits the height of the screen or device, and resizes responsively without cropping when the device height changes. How can I achieve this? If you need a visual example of what I mean, ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

Different option for animated side slider based on location

Whenever I click on this div, it slides out smoothly. Check out these images to get a visual of what I am aiming for: This is how the Div looks when collapsed by default https://i.stack.imgur.com/zJIsA.png Once slid out, the Div looks like this (highlig ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

Is it possible to decode a two-dimensional array of objects in JSON?

My scenario involves a two-dimensional array of objects structured as follows: function test(n){ this.id = n; } var testArray= new Array(2); for(i = 0; i < testArray.length; i++){ testArray[i] = new Array(2); for(j = 0; j < testArray[i].lengt ...

Display a div every 3 seconds with the help of jQuery

I am seeking a solution to display the second div (box2) every 3 seconds. Can anyone help me achieve this using jQuery? <div id="box1" style="background-color:#0000FF"> <h3>This is a heading in a div element</h3> <p>This ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

Tips for displaying axios status on a designated button using a spinner

Utilizing a v-for loop to showcase a list of products retrieved from an API request. Within the product card, there are three buttons, one for adding items to the cart with a shopping-cart icon. I aim for the shopping-cart icon to transform into a spinner ...

Dimensions of CSS Buttons

On my screen, I have 3 buttons with varying sizes determined by their padding. As the text wraps within each button, they adjust in height accordingly. However, the issue arises when the buttons end up being different heights. Instead of setting a specific ...

Using track by in ng-repeat function triggers an endless $digest-loop issue

It appears that I am still struggling to grasp the mechanism behind ng-repeat, $$hashKeys, and track by. Currently, in my project, I am working with AngularJS 1.6. The Issue: I have an array of complex objects that I want to display as a list in my view ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

Is it possible to change text dynamically with an input box using JavaScript?

Is there a way to use JavaScript to create two input boxes for text replacement? Instead of constantly editing code to replace different text, I am looking for a simple user interface with Input Box A, Input Box B, and a button. The first input box will ...

"Learn how to handle exceptions in Nest JS when checking for existing users in MongoDB and creating a new user if the user does

Below is the implementation of the addUser method in users.service.ts - // Function to add a single user async addUser(createUserDTO: CreateUserDTO): Promise<User> { const newUser = await this.userModel(createUserDTO); return newUser.save() ...

When a block reaches a certain height, the mat-chip-list in Angular Material is automatically shortened to fit. This feature is exclusive to

<div fxFlex="100" fxFlex.gt-sm="80" fxFlex.sm="100"> <div *ngFor="let permission of arrayOfObjectPermissions; let index = z" class="permissions-list"> <mat-card [title]=&qu ...

When mousing over a subitem of the Image menu, ensure that the Image menu

Is there a way to prevent the image menu from reverting back to its original image when hovering over its subitems? I have 5 navigation menu items, but only one has a dropdown. Whenever I hover on the subitems of About Us, the image for About Us changes ba ...

Utilizing an Object in Option Select with ngModel

Currently, I am working on creating a date-time selector in Angular and facing challenges with incorporating an object using ng-model. My dilemma lies in utilizing a hash of hours that have values ranging from 1 to 12, each corresponding to 'AM' ...

CSS table property remains unchanged following an ajax request

At first, my table is set to display none, making it invisible in the application. I am using an ajax call so that when a user selects an option, a table is generated and the display property changes from none to block, making it visible. However, the tabl ...