Skip to content

Instantly share code, notes, and snippets.

@esgy
Created August 4, 2014 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save esgy/815a7b064d5cfdd5c36f to your computer and use it in GitHub Desktop.
Save esgy/815a7b064d5cfdd5c36f to your computer and use it in GitHub Desktop.
Angular SlickJs directive with reinit support
'use strict';
angular.module('app')
.directive('sgSlick', ['$timeout', function ($timeout) {
return {
restrict: 'AE',
scope: {
images: '=',
selectedImage: '=',
lazyLoad: '@',
arrows: '@',
dots: '@',
infinite: '@',
autoplay: '@',
slidesToShow: '@',
slidesToScroll: '@',
cssEase: '@'
},
link: function (scope, el, attrs) {
var slickOptions = {
lazyLoad: scope.lazyLoad || 'ondemand',
arrows: scope.arrows || true,
dots: scope.dots || true,
infinite: scope.infinite || false,
autoplay: scope.autoplay || false,
slidesToShow: scope.slidesToShow || 4,
slidesToScroll: scope.slidesToScroll || 4,
cssEase: scope.cssEase || 'linear'
};
var slideTpl = function (img) {
return '<div><img src="' + img.small + '" data-id="' + img._id + '" ></div>';
};
scope.$watch(function () { return scope.images; }, function (newVal, oldVal) {
$timeout(function () {
// slick was already initialized
if (el.hasClass('slick-initialized')) {
// destroy slick and remove html content
el.unslick();
el.html('');
// create slick again
el.slick(slickOptions);
// re add slides
_.each(scope.images, function (img) {
el.slickAdd(slideTpl(img));
});
//el.slickGoTo(scope.images.length);
} else {
// Initialize slick
el.slick(slickOptions);
//add slides
_.each(scope.images, function (img) {
el.slickAdd(slideTpl(img));
});
}
// on image click, update the selected image scope model
el.find('img').on('click', function (e) {
var selectedImgId = $(this).data('id');
scope.selectedImage = _.find(scope.images, {'_id': selectedImgId});
scope.$apply();
});
}, 100);
}, true);
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment