Guide to creating nested collapsing rows in AngularJS

My attempt to implement expand and collapse functionality in AngularJS for a section is not yielding the desired result.

To demonstrate, I created a simple demo of collapsible/expandable sections in AngularJS which works fine. You can view it here. The example showcases the functionality with a collapsible/expandable first row.

I then applied the same concept to another example where I have a table with different sections such as GENERAL_INFORMATION and USER_INFORMATION that I want to collapse/expand. My code for this can be found here.

<tr ng-repeat="(key, value) in name">
    <uib-accordion>
      <div uib-accordion-group class="panel-default" is-open="status.open">
          <uib-accordion-heading>

            <td ng-if="value.type == 'LABEL'" colspan="2" style="background: #777; color: white;">
                {{key}}
            </td>
          </uib-accordion-heading>
      </div>
   </uib-accordion>

    <td ng-if="value.type == 'FIELD'">{{key}}
        <span ng-if="value.required">
            <sup class="required">*</sup>
        </span>
    </td>
    <td ng-if="value.type == 'FIELD'"
    >
        {{value.value}}
    </td>      
</tr>

Any suggestions on how to improve this implementation?

Answer №1

By utilizing foundational AngularJS techniques, you can achieve the desired effect by combining ng-if with a toggleable show variable.

If you have multiple heading and content pairings, an array of show can be used to accomplish this.

This code snippet showcases the basic approach. However, for a cleaner implementation, consider encapsulating the functionality in a directive similar to the uib-accordion.

angular.module('myApp', ['ngAnimate'])
  .controller('myController', ['$scope', function($scope) {
    $scope.show = [];
    $scope.show[0] = false;
    $scope.show[1] = false;

    $scope.toggle = function(index) {
      $scope.show[index] = !$scope.show[index];
    };
  }]);
table {
  width: 100%;
}

.heading {
  height: 48px;
  background-color: #555;
  color: #fff;
  cursor: pointer;
}

.content {
  background-color: #eee;
  height: 150px;
  transition: all 3s ease-out;
}


/* The initial CSS styles for the enter animation */

.fade.ng-enter {
  transition: 0.5s linear all;
  opacity: 0;
}


/* The final CSS styles for the enter animation */

.fade.ng-enter.ng-enter-active {
  opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular-animate.js"></script>

<div ng-app="myApp">
  <table ng-controller="myController">
    <tr class="heading">
      <td ng-click="toggle(0)">
        Heading
      </td>
    </tr>
    <tr ng-if="show[0]" class="fade">
      <td class="content">
        Content
      </td>
    </tr>
    <tr class="heading">
      <td ng-click="toggle(1)">
        Heading
      </td>
    </tr>
    <tr ng-if="show[1]" class="fade">
      <td class="content">
        Content
      </td>
    </tr>
  </table>
</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

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...

Issues persist with Ajax form submissions; the submitted data never seems to go through

I have encountered variations of this issue multiple times, but despite analyzing numerous examples, I am unable to determine why my code is not functioning properly. <script> $('document').ready(function(){ $('datafixForm' ...

Moving information from Ajax to PHP

I'm experiencing an issue with sending data from AJAX to PHP on the same site, "testpage.php". The PHP script doesn't seem to be displaying the data being sent. Using jQuery/Ajax: <script src="http://code.jquery.com/jquery-latest.js" type="t ...

Creating a feature in Angular JS that allows for each item in a list to be toggled individually

Looking for a more efficient way to toggle individual buttons without updating all at once? Check out this basic example where each button toggles independently by using ng-click="selected = !selected". Instead of updating all buttons at once, you can achi ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...

The synchronization between jQuery's onLoad and onDomready functions allows for seamless

When utilizing jsFiddle, I have noticed two options for initializing content using jQuery: onLoad or onDomReady. I have tested most of the scripts I've written and found no noticeable functional difference. Upon researching via Google, I discovered o ...

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

Retrieve an element generated by a React script without using the ref attribute

There is a chat button on my website generated by a script (zendesk chat) that creates an iframe with the ID "launcher". I am using Nextjs and I am trying to access this element, but I am unable to attach a ref since I do not have the code. I have been sea ...

What could be the reason for JavaScript code successfully exporting to Excel using the old office extension .xls but encountering issues when trying to export

I am currently working on exporting an HTML table to Excel using JavaScript. I have encountered an issue where it does not export to the newer version of Excel with the xlsx extension. However, it works fine and exports to older versions of Excel with the ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

What is the best way to pass the index value of a v-for loop as an argument to a computed property function in Vue?

I'm looking to pass the index value from a v-for loop (inside a path tag) as a parameter to a function stateData(index) defined in a computed property in Vue. I attempted to achieve this using v-model="stateData[index]", but an error is being displaye ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

Denied access to [Any Url] as it breaches the specified Content Security Policy directive and refused to connect

Struggling to retrieve data using the Login() method within a post request, but encountering an error when the URL is transferred to its destination. Error: Refused to connect to 'http://smartlearner.com/SmartLearner/UserAccount/[email prote ...

Choosing the Active Browser Tab while Modal is Open in Angular

In my current situation, I have implemented a function in the first tab that displays a modal or component after 5 seconds: ngOnInit() { setTimeout(() => { this.openDialog(); }, 5000); } openDialog() { this.dialog.open(.....); } However, if ...

Is there a way to begin using the :nth-child() selector from the last element instead of the first?

$('button').click(function(){ $('ul').find('li:nth-child(2)').css('color', '#f00') }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> < ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...