AngularJS - UI Bootstrap: Easily expand or collapse all items in the Accordion widget

I have created a code to open and close all tabs of an accordion individually using separate 'open' and 'close' buttons. However, it requires me to dynamically add a key value pair (a Boolean value) to my JSON data.

What is the best approach in this scenario? Should I add the Boolean value as a static element in the JSON or is it acceptable to dynamically add values when they are purely for visual structure and not related to actual object data?

HTML/Angular directives

<div id="app" ng-app="demoApp">
  <div id="controller" ng-controller="demoAppCtrl">    
    <uib-accordion close-others="false">    
      <div class="btn-group form-group">
        <button type="button" class="btn btn-warning" ng-click="toggle(true)">Open</button>
        <button type="button" class="btn btn-warning" ng-click="toggle(false)">Close</button>
      </div>      
      <uib-accordion-group is-open="hero.state" ng-click="setOpened(false)" ng-repeat="hero in heroes">
        <uib-accordion-heading>
          {{hero.name}}
        </uib-accordion-heading>
        {{hero.bio}}
      </uib-accordion-group>    
    </uib-accordion>    
  </div>  
</div>

Javascript/Angular

var app = angular.module('demoApp', ['ngAnimate','ui.bootstrap']);
app.controller('demoAppCtrl', function($scope) {

  // This json object contain only one entry as an example
  $scope.heroes = [
    {'name': 'Captain America', 'team': 'Avengers', 'bio': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae metus placerat, condimentum nisl et, accumsan sapien. Quisque molestie magna nulla, id malesuada sem interdum a.'}
  ];

  $scope.addDefaultState = function(val) {
    for (var i=0;i<$scope.heroes.length;i++) {
      $scope.heroes[i].state = val;
    }
  } 
  $scope.addDefaultState(false);

  $scope.toggle = function(status) {
    $scope.heroes.forEach(function(e) {
      e.state = status;
    });
  }

});

codepen.io - Working example (with corrections)

Answer №1

In my personal view, I believe that the static json should not include a Boolean state value. It is more fitting to dynamically incorporate values for visual representation purposes.

Regarding your code, the function addDefaultState serves no purpose. The use of is-open="hero.state" will automatically handle the default state because initially it will register as false if no state is found. Therefore, by making some modifications to your code as shown below, it should still function effectively:

var app = angular.module('demoApp', ['ngAnimate','ui.bootstrap']);
app.controller('demoAppCtrl', function($scope) {

  // This example JSON object contains only one entry 
  $scope.heroes = [
    {'name': 'Captain America', 'team': 'Avengers', 'bio': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae metus placerat, condimentum nisl et, accumsan sapien.'}
  ];

  $scope.toggle = function(status) {
    $scope.heroes.forEach(function(e) {
      e.state = status;
    });
  }

});

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

When utilizing React client-side rendered components, the state may fail to update while the script is actively running

I am currently facing an issue for which I don't have a reproducible example, but let me explain what I'm trying to do: class MyComponent extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

A distinctive noise is heard when hovering over multiple instances of a div

I'm trying to implement a feature where a unique sound plays when hovering over a specific div element with a particular class (.trigger). However, I am encountering an issue where multiple instances of this div class result in the same sound being pl ...

What is the process for incorporating a full-page blog into a blog preview?

I customized a template, but there is a blog section within the div that I am struggling to replicate. Here is the test website for reference: Below is the HTML code for the blog section: <!-- Blog Start --> <section class="section bg ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

The Firebase child_changed event may occasionally be missed at random intervals when the browser tab is inactive

I am currently developing a real-time application where one user can enter the app, and all other users connected to that session will receive notifications or payloads of what that user is entering. Below is the Firebase child_changed listener that every ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

The output of PHP is not being captured by Ajax

I have a JavaScript code that calls a PHP script to retrieve a value, but it's not working as expected. Here is my JavaScript code: $.ajax({ type: 'GET', url: '/home/example.com/ftp/www/typo3conf/ext/quiz_rs/pi1', data ...

Jquery debugger keeps getting triggered multiple times by checkbox interactions

I've encountered an issue while working on Mvc.Grid that involves the onclick event of a checkbox. Within the grid, each row represents a Profile and contains a checkbox for selection. My goal is to retrieve a list of IDs corresponding to the checked ...

How do I display form results in JSON format after submission in Laravel?

Is there a way in Laravel to display form results in JSON format without needing to save them to the database first? The purpose is to verify and validate the data entered in the form. ...

Changing the value of a specific array element after removing it from a filtered ng-repeat resultList

I have a list of users where you can select a user by clicking on it, which then places the selected element into an object called $scope.selectedMember. The ng-repeat directive is being used along with a filter in a search box. It's crucial that $sco ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Ways to bring in external javascript files in reactjs

I'm currently working on a form that requires the user to input their location. To achieve this, I have integrated the npm package react-geosuggest-plus. However, I want to avoid including <script src="https://maps.googleapis.com/maps/api/js?key=AI ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...

at" symbol used as a parameter indicator in defining resources

According to the information provided in the documentation (http://docs.angularjs.org/api/ngResource.$resource): The syntax for using $resource is as follows: $resource(url[, paramDefaults][, actions]); The optional parameter paramDefaults represents the ...

Locating items within an array of objects using Angular 6 with TypeScript or JavaScript

I have the following code in my HTML template for my Angular 6 application. <div *ngIf ="conversation.participants[conversation.updatedBy.toLowerCase()].firstName">somedata </div> My goal is to search within the participants array object base ...

Using mappers to create a computed property for two-way binding

In my Vue 2 project, I make use of vuex. Currently, I am working on implementing two-way binding for this HTML element: <input v-model="message"> computed: { message: { get () { return this.$store.state.obj.message }, ...

What is the best method to extract data from JSON in a targeted manner?

I am eager to enhance my understanding of JSON by using Python. One query I have pertains to accessing elements within the data. To illustrate, consider the following generic JSON information: "data":{ "Bob":{ "name":"Bob", "age":"30", ...

How can I form a dataframe using a nested list of lists in Python?

Here is a list that I would like to convert into a dataframe: [[{"1":"","2":"","3":"Jurisdiction of"},{"1":"Name of Subsidiary","2":"","3":"F ...