Troubleshooting problems with ng-repeat integration in Bootstrap and AngularJS

I am currently in the process of developing an application using Bootstrap and AngularJS. One issue I have encountered involves using ng-repeat within a col-md-3 to list products. The challenge lies in wanting to incorporate a collapse feature into the grid, but due to the automatic generation of columns, I am unsure of how to proceed.

To better illustrate my dilemma, consider the following diagram: Initially, the grid is populated with .col-md-3 elements through ng-repeat.

My goal is to introduce a .col-md-12 that will appear directly below the row corresponding to the clicked .col-md-3 element.

Initially, I thought about dynamically adding an empty .col-md-12 after every set of 4 .col-md-3 elements, but implementing this approach seems challenging. Does anyone have any alternative suggestions?

Here is the relevant html:

<div class="infinite" infinite-scroll="loadDetails()">
      <div class="col-xs-3 col-md-3" ng-repeat="release in main.releases | filter:main.album">
        <release release="release" artist="main.artist" class="dropdown"></release> 
      </div>
</div>

EDIT: For those interested, here is a live Plunker demo showcasing tasseKATT's proposed solution.

Answer №1

Implement a unique custom directive on each inner element along with a position counter that starts at 1 and a marker indicating if it's the last element:

<div ng-repeat="item in items" class="col-xs-3">
  <div class="item" my-directive position="{{ $index + 1 }}" last="{{ $last }}">
  </div>
</div>

Create the directive using an isolated scope, bind scope properties to the values of the position and last attributes, and add a click event handler to the element:

app.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: { position: '@', last: '@' },
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        ...
      });
    }
  };
});

In the click handler, first create the collapse element or select it if it already exists:

var collapseQuery = document.querySelector('#collapse');
var collapse = collapseQuery === null ?
angular.element('<div id="collapse" class="col-xs-12"><div class="twelve"></div></div>') :
angular.element(collapseQuery);

Based on the position of the clicked element, calculate the next multiple of four:

var calculatedPosition = Math.ceil(scope.position / 4) * 4;

Retrieve the element at the calculated position or the last one if the position is out of range:

var calculatedQuery = document.querySelector('[position="' + calculatedPosition + '"]');
if (calculatedQuery === null) calculatedQuery = document.querySelector('[last="true"]');;

var calculatedElement = angular.element(calculatedQuery);

Insert the collapse element after the element at the calculated position:

calculatedElement.parent().after(collapse);

There may be room for optimization, but this should guide you in the right direction.

Check out a demo with additional visuals here: http://plnkr.co/edit/fsC51vS7Ily3X3CVmxSZ?p=preview

Answer №2

To approach this question from an angular perspective and follow the bootstrap convention of using 12 columns in a row, consider the following:

When creating grid columns, specify how many of the twelve available columns you want to span. For instance, three equal columns would be represented by three .col-xs-4.

In your situation, each row can contain up to 4 .col-xs-3 columns or just one .col-xs-12. Organize your data accordingly by breaking it down into smaller arrays.

$scope.getRows = function(array) {
var rows = [];

var i,j,temparray,chunk = 4;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);

    rows.push(temparray);
}

return rows;
};

$scope.rows = $scope.getRows($scope.main.releases);

You can then utilize nested ngRepeat with ng-if to achieve the desired layout. The ng-if directive ensures that a col-xs-12 is generated only when a corresponding .col-xs-3 is clicked.

<div ng-repeat="row in rows">
  <div class="row">
    <div class="col-xs-3" ng-repeat="release in row" ng-click="main.releaseClicked=release">
      <div class="release">{{release}}</div> 
    </div>
  </div>
  <div class="row" ng-repeat="release in row" ng-if="main.releaseClicked==release">
    <div class="col-xs-12">
      <div class="detail">Release detail: {{release}}</div>
    </div>
  </div>
</div>

This approach provides a more declarative view of how the app functions without relying on jQuery for DOM manipulation.

For a demonstration, check out this working demo: http://plnkr.co/ujlpq5iaX413fThbocSj

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

Transforming an array into an object for generating a JavaScript report

I am trying to organize data from an array that represents a table. The array looks like this: table = [['john', 'male', 24, '12/12/12'], ['jane', 'female', 24, 12/12/12]] The goal is to allow the user t ...

Navigate to a specified div using JavaScript

I'm having an issue with my navigation bar not scrolling to the designated div. Despite looking at other examples, I can't seem to find a solution <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> ...

Why is the React onClick method returning undefined upon the first selection, and why are the values being passed not consistent with

While attempting to create a list of users that, when clicked, should open up a corresponding user's message, I encountered an issue where clicking for the first time resulted in an 'undefined' value being passed. I've tried troublesho ...

The event listener for browser.menus.onClicked is dysfunctional in Firefox

Currently, I am in the process of developing my own Firefox extension and I have encountered an issue with adding a listener to an onclick event for a context menu item. manifest.json { "manifest_version": 2, "name": "My exten ...

The results obtained from using $http get are not the same as those obtained

While attempting to retrieve user reports using a User $resource, I encountered an unexpected object format in the returned result: {0: "n", 1: "a", 2: "m", 3: "e", 4: ",", 5: "e", 6: "m", 7: "a", 8: "i", 9: "l", 10: ",", 11: "p", 12: "a", 13: "r", 14: "t ...

Step-by-step guide on preventing an item from collapsing in a Bootstrap navbar

Is there a way to exclude a specific item from the navbar collapse box when the screen size becomes small? Here is the current HTML code: <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> ...

Switching the buttons' values to correspond with JavaScript functions

I'm trying to modify my web page so that I can change the content of an <iframe> using two buttons: Before and After. Before After Currently, I have buttons with the values Previous and Next. In order to achieve what I want, I need to create ...

Angularjs's approach to managing HTTP connections through connection pooling

In the process of generating numerous requests from my angularjs application to a backend REST server, I am utilizing the http service to initiate calls. My objective is to manage the concurrency of requests sent to the server as I am aware that the browse ...

Invalid input: database object is missing

I have integrated "express": "3.2.6", and nodeJS v0.10.25. Upon running my app.js, I encountered the following error: TypeError: Object #<IncomingMessage> has no method 'getConnection' This is what my index.js file looks like: /* * GET ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

Replicated shadows brought to life in three.js

I've been experimenting with shadows in three.js and have encountered a problem where the shadow is being cast on two faces of a mesh, as shown here. It's puzzling that the shadow from the "head" of my character is appearing on two faces of the ...

Nginx is responsible for handling files for routes that are not found within the AngularJS application

I have successfully created an AngularJS app (v1) that is packaged as a Docker image with Nginx as the web server. I need the app to display index.html when users navigate to http://localhost:5000/content and login.html when they go to http://localhost:500 ...

The anchorEl state in Material UI Popper is having trouble updating

I am currently facing an issue with the Material UI popper as the anchorEl state remains stuck at null. Although Material UI provides an example using a functional component, I am working with a class-based component where the logic is quite similar. I w ...

Nested views within Angular providing a multitude of perspectives

Currently, I am tackling a project at my workplace with my colleagues, but we are collectively stumped on how to proceed. Consequently, the details may come across as nebulous. Allow me to present a preview of the expected layout: Template The plan is fo ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Can trusted events in Chrome trigger a timeout with Synchronous Ajax requests?

Situation We are facing a situation where we need to open a new tab in browsers after an XHR / Ajax request is made by clicking on something. To achieve this, we set the Ajax request to be synchronous in order to maintain the context of the trusted click ...

What is the best way to utilize {...this.props} within a functional component?

I recently purchased a React-Native course on Udemy where the instructor used {...this.props} but unfortunately, it caused an error for me. The error message I received was: TypeError: undefined is not an object(evaluating '_this.props') Any ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...