How to reinitialize Elastislide carousel with a new image set - using angularjs

881 views Asked by At

I am using angularjs and would like to show/hide a carousel on a page. Based on events on the page, I would like to remove and later display the carousel again with a distinct set of images. The following directive works to initially load the carousel. I was trying to use angular's show/hide in combination with Elastislide's add() function.

In the following code, the carousel initializes and works as expected. The problem is when the broadcast message is received to update the carousel, any change to $scope.images causes the all images in the carousel to disappear. Subsequently, the carousel.add() does nothing.

EDIT Probably add() is not appropriate for what I'm trying to do. I believe a better design will be to have a hook to remove the carousel and another hook to re-initialize the elastislide plugin with a new set of data.

myModule.directive('myCarousel', ['$compile', function($compile) {

var carousel;

var linker = function(scope, element, attrs) {

    scope.$watchCollection('images.length', function () {
        if (! carousel) {
            carousel = element.elastislide();
        } else {
            carousel.add();
        }
    });

};

var controller = function ($scope) {

    $scope.$on('updateCarousel', function(evt, imgs) { 
        $scope.images.push({src: "./Elastislide/images/small/20.jpg", alt: "image20"})
    });

    $scope.images = [
        { src : "./Elastislide/images/small/1.jpg", alt : "image01" },
        { src : "./Elastislide/images/small/2.jpg", alt : "image02" }];

};

return {
    restrict : 'A',
    link : linker,
    controller : controller
};
}]);

With the following markup

    <ul my-carousel id="carousel" class="elastislide-list">
        <li ng-repeat="img in images"><a href="#"><img src="{{img.src}}" alt="{{img.alt}}" /></a></li>
    </ul>
1

There are 1 answers

0
Tamura On

If you want to implement carousel on AngularJS app easily, ng-carousel is convenient.