SamiX SamiX - 1 month ago 19
AngularJS Question

angular-ui: Trigger events on Carousel

I'm using angular-UI's Carousel and i want to trigger the "prev" and "next" events from my controller.

There was issue about it on Github, but its seems not to be handled actually: https://github.com/angular-ui/bootstrap/issues/1836

the Carousel page with the plunker example: http://angular-ui.github.io/bootstrap/

Any idea on the best approach ?
Thank you!

Answer

You can create a custom directive that exposes the next and previous methods of the carousel on your scope:

Plunker Demo

app.directive('carouselControls', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      scope.goNext = function() {
        element.isolateScope().next();
      };
      scope.goPrev = function() {
        element.isolateScope().prev();
      };

    }
  };
});

Add the directive to your carousel element and then you can call the goPrev or goNext methods on your controller scope.

<carousel carousel-controls ... ></carousel>
//Call goNext() or goPrev() such as:
<button class="btn btn-primary" ng-click="goNext()">Next Slide</button>

It's a pretty straightforward directive, but here's how it works:

The carousel has methods $scope.next and $scope.prev, but we can't access them directly from the controller because the carousel has an isolated scope. To expose them, in the carouselControls link function, we create two methods goNext and goPrev, which we add to the scope for the carouselControls.

Since carouselControls doesn't have an isolated scope, the scope passed to the link function is the scope of its parent controller. We use these methods to call the next or prev methods on the isolatedScope of the element (which is the carousel element because that's where we place our carouselControls directive).

Comments