-->

Get active slide index outside angular-ui bootstra

2020-07-24 15:55发布

问题:

I have a problem getting the active slide in an Angular-UI Bootstrap carousel outside the carousel.
I have a panel, with the carousel inside, and want to put buttons in the footer of the panel that makes actions using the selected slide, but using jquery selectors is not an option.

I want to implement it using something in pure angular.
I think I can use the active attribute, but maybe there is something clever that can do the trick more smoothly.

Some code (Jade syntax):

.panel.panel-info
  .panel-body
    carousel.imgCarousel(interval='5000')
      slide(ng-repeat='media in selCard.superviseTab.media')
        img.img-responsive(preload-image ng-src='/api/cards/{{selCard.superviseTab.sID}}/media/{{$index}}')
        .carousel-caption
          multiSelect
          h4 Slide {{$index+1}} of {{selCard.superviseTab.media.length}}
          p {{media.originalFilename}}
  .panel-footer
    .navbar-collapse.collapse
      ul.nav.navbar-nav.navbar-left
        li
          a.btn.btn-danger
            i.fa.fa-unlink

回答1:

If you look at the AngularUI documentation, you can see this is how the slides are integrated into the HTML:

<carousel interval="myInterval">
  <slide ng-repeat="slide in slides" active="slide.active">
    ...
  </slide>
</carousel>

We can see that the active slide is determined by the active property on each slide.
So, you should be able to iterate through the slides and return the first slide with the active property on it. As long as you haven't modified the slides array outside of this carousel, it should give you the index of the current slide.

For example, something like:

function isActive(slide) {
  return slide.active;
};
$scope.getActiveSlide = function() {
  var activeSlides = $scope.slides.filter(isActive)[0]; 
  //return the first element, since the array should only return one item
};

Should do the job (or however you choose to implement your find functionality).