AngularJS ng-repeat重复active类致Bootstrap轮播故障求助
Fix: AngularJS ng-repeat Adding
active Class to All Bootstrap Carousel Items Got it, let's fix this Bootstrap carousel issue with AngularJS right away. The problem here is that you're hardcoding the active class on the element with ng-repeat—so every single carousel-item gets that class, which breaks Bootstrap's carousel logic (it only expects the first item to be active initially).
Here's the corrected code, with two key fixes:
- Use
ng-classto only apply theactiveclass to the first item in theng-repeatloop - Dynamically generate carousel indicators to match the length of your
ActiveSinger.albumsarray (instead of hardcoding 4 indicators, which will break if your album count changes)
<div class="modal fade" id="SingerAlbum"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-body"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <!-- Dynamically generated indicators --> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="{{index}}" ng-repeat="(index, album) in ActiveSinger.albums" ng-class="{'active': $first}" ></li> </ol> <div class="carousel-inner"> <!-- Only add 'active' class to the first carousel item --> <div class="carousel-item" ng-repeat="album in ActiveSinger.albums" ng-class="{'active': $first}" > <img class="d-block w-100" ng-src="{{album.album_cover}}" alt="{{album.slide_number}}"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div>
Key Explanations:
ng-class="{'active': $first}": AngularJS provides special variables inng-repeatloops, and$firstistrueonly when we're rendering the first element of the array. This ensures only the first carousel item and indicator get theactiveclass—exactly what Bootstrap needs.- Dynamic Indicators: By using
ng-repeaton the indicators, you don't have to manually update their count if yourActiveSinger.albumsarray grows or shrinks. Thedata-slide-to="{{index}}"binds each indicator to the correct carousel item index.
After making these changes, your carousel should work as expected—no more stacked images, and Bootstrap will handle the slide transitions automatically once it has the correct initial active item.
内容的提问来源于stack exchange,提问作者mohammad maleki
相关产品推荐
相关产品推荐

