AngularJS and Bootstrap carousel combined for a dynamic multi-item per slide display

Currently, I am utilizing Bootstrap to showcase a carousel on my website, where multiple items are displayed per slide as demonstrated in this example. The use of static images has yielded satisfactory results, as evidenced by the jsFiddle example found here (ensure that the display frame is sufficiently large to avoid any issues caused by Bootstrap's media queries, which will be addressed later).

Nevertheless, I am now attempting to define the content of the carousel using a variable and bind it with AngularJS through an ng-repeat directive. However, an issue arises where only the image identified as the "active" item is being displayed. This behavior differs from when statically defined images were used. To see the problem in action, refer to this jsFiddle.

Here are some solutions I have attempted so far :

  • Show all items and set overflow:hidden
  • Adjust item size to 33% and display all items instead of using the col-md-4 class

HTML

<div class="carousel-started-themes" style="height:150px; width:700px;">
  <div class="carousel slide" id="myCarousel">
    <div class="carousel-inner">
      <div class="item" ng-class="{active:!$index}" ng-repeat="img in image">
        <div class="col-md-4"><a href="#"><img ng-src="{{img}}" class="img-responsive"></a>
        </div>
      </div>
    </div>
    <a class="left carousel-control" href="#myCarousel" data-slide="prev" style="z-index:10000;"><i class="glyphicon glyphicon-chevron-left"></i></a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next" style="z-index:10000;"><i class="glyphicon glyphicon-chevron-right"></i></a>
  </div>
</div>

JS

function MyCtrl($scope) {
  $scope.image =["https://wallpaperscraft.com/image/minimalism_sky_clouds_sun_mountains_lake_landscape_95458_1600x900.jpg", "https://wallpaperscraft.com/image/clouds_milky_way_eclipse_light_68883_1600x900.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSl5bsNT-Qtm0tfbydXFMuFCG27Kug6D5Z3hrgitIQqQq22Da95Ig", "https://wallpaper.wiki/wp-content/uploads/2017/05/Photos-1600x900-Wallpapers-HD.jpg", "https://wallpaperscraft.com/image/torzhok_tver_region_evening_sunset_river_reflection_autumn_russia_58028_1600x900.jpg", "https://wallpaper.wiki/wp-content/uploads/2017/04/wallpaper.wiki-1600x900-HD-Image-PIC-WPD0014727.jpg"];
}

$('#myCarousel').carousel({
  interval: false
});

$('.carousel .item').each(function() {
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  if (next.next().length > 0) {
    next.next().children(':first-child').clone().appendTo($(this));
  } else {
    $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
  }
});

Answer №1

Is there a necessity to display or hide content? Consider utilizing overflow:hidden; in conjunction with jquery for horizontal scrolling without a scroll bar. This approach eliminates the need for hiding any elements.

Answer №2

After some investigation, I managed to find the answer.

The issue stemmed from jQuery executing too quickly, not properly waiting for ng-repeat to finish before binding the data and creating multiple display elements.

To resolve this, I implemented a helpful callback directive and moved the jQuery methods inside the callback function.

The custom directive used:

app.directive("repeatEnd", function(){
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                if (scope.$last) {
                    scope.$eval(attrs.repeatEnd);
                }
            }
        };
    });

While this improved the situation, there was still an Angular binding issue due to elements being bound after the ng-repeat completes. To address this challenge, I modified the jQuery code to utilize the index of the current element in ng-repeat and retrieve data accordingly:

$scope.repeatOver = function(){

        $('#myCarousel').carousel({
          interval: false
        });

        $('.carousel .item').each(function(index){
          var next = $(this).next();
          var indexNext = index+1;
          var indexNextNext = index+2;
          if (!next.length) {
            next = $(this).siblings(':first');
            indexNext = 0;
            indexNextNext = 1;
          }
          next.children(':first-child').clone().appendTo($(this));
          // Update the element source
          $(this).children(':first-child').next()[0].getElementsByTagName('img')[0].src = $scope.image[indexNext];

          
          if (next.next().length>0) {
            next.next().children(':first-child').clone().appendTo($(this));
            // Change the source of the element
            $(this).children(':first-child').next().next()[0].getElementsByTagName('img')[0].src = $scope.image[indexNextNext];
          }
          else {
            indexNextNext = 0;
            $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
            // Change the source of the element
            $(this).children(':first-child').next().next()[0].getElementsByTagName('img')[0].src = $scope.image[indexNextNext];
          }
        });
    }

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

Issues with React JS and JavaScript filtering functionality not working correctly

I've been working on implementing a filter feature for a website, using an HTML range slider. However, I've encountered an issue where the values only update correctly when decreasing. For example, if I set the slider to $500, only products that ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

A valid path is required in the form of a string when working with the HTTP module in Node.js

Currently, I'm working on an update checker that doesn't involve downloading the update. My main goal is to compare the version in the package.json file on GitHub with the one in my Electron app. However, when using this code, I encountered a "p ...

Remove a specific line from a PHP script

I have developed a system of alerts that allows users to delete an alert if they choose to do so. Below is the code for the delete button and table: <button type="button" name="Delete" Onclick="if(confirm('Are you sure you ...

Utilizing React Typescript for Passing Props and Implementing them in Child Components

I'm currently working with React and TypeScript and attempting to pass data as props to a child component for use. However, I've encountered an error that I can't quite understand why it's happening or how to resolve it. Additionally, I ...

Struggling with fixing a 500 error caused by angular routing? Let us assist you

Struggling with resolving the 500 issue. Unsure if changes need to be made in express or angular. Here is my main.js public code snippet. Any assistance would be greatly appreciated. var app = angular.module('myApp', ['ui.router'], fun ...

What is the reason behind fixing an overflow issue simply by moving the mouse outside of a container in IE7 and HTML?

My webpage includes a series of questions, with each question being displayed or hidden based on the answer to the previous question. Occasionally, after toggling back and forth between questions, I notice that the final question appears below its designa ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

What steps can be taken to reduce the size of the cards in ant.design?

Currently, I am using the ant.design Card component to present messages in a chat webapp built with react/redux. However, each card is displaying too much space around the text. Is there a way to adjust the card so that it wraps the text more closely? htt ...

Can you explain the meaning of -ms-value?

I recently came across a solution for an issue specific to IE, and it worked perfectly for me. You can find the solution here: Change IE background color on unopened, focused select box However, I'm still puzzled about the meaning of -ms-value. Any i ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to al ...

Utilizing the Angular directive md-autocomplete alongside the Google Maps autocompleteService for seamless integration

Greetings and thank you for taking the time to assist me. I have been diligently working on setting up an autocomplete search box that interacts with the Google AutocompleteService API using Angular. Currently, my Angular AutocompleteService is functioni ...

Attempting to close a basic angular modal leads to an error message stating: Property 'dismiss' cannot be read because it is undefined

I am attempting to create a straightforward modal that appears when a user clicks on a section of my demo app that is still in progress. Everything is functioning correctly until the point where I require the user to click the 'Close' button on ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Using jQuery to change the `class` of the parent `div` based on the length of a `p`

I am attempting to adjust the height of a parent div based on the length of text in its child p.descr. This is achieved by adding a specific class that corresponds to different height values in CSS. Below is the jQuery code snippet: $(document).ready(fu ...

Two variations of identical descriptions within a single div container

Is there a way for me to use an item, specifically an img, within the same div class but with different definitions? For example: section .row img { margin: 0 0 30px; width: 100%; border: 4px solid #18a00e; } section .row img { margin: 0 ...