bz-slider.src.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. (function(angular, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. define('bzSlider', ['angular'], function($, angular) {
  4. return factory(angular);
  5. });
  6. } else {
  7. return factory(angular);
  8. }
  9. }(angular || null, function(angular) {
  10. var app = angular.module('bzSlider', []);
  11. var bzSliderController = ['$scope', '$timeout', '$parse', function ($scope, $timeout, $parse) {
  12. var timeOut = null;
  13. $scope.$slides = $scope.$slides || [];
  14. $scope.$play = false;
  15. $scope.play = function() {
  16. timeOut = $timeout(function() {
  17. $scope.next();
  18. $scope.play();
  19. }, $scope.$delay || 2000);
  20. $scope.$play = true;
  21. };
  22. $scope.stop = function() {
  23. $timeout.cancel(timeOut);
  24. timeOut = null;
  25. $scope.$play = false;
  26. };
  27. $scope.next = function() {
  28. var total = $scope.$slides.length;
  29. if (total > 0) {
  30. $scope.$slideIndex = ($scope.$slideIndex == total - 1) ? 0 : $scope.$slideIndex + 1;
  31. }
  32. };
  33. $scope.prev = function() {
  34. var total = $scope.$slides.length;
  35. if (total > 0) {
  36. $scope.$slideIndex = ($scope.$slideIndex == 0) ? total - 1 : $scope.$slideIndex - 1;
  37. }
  38. };
  39. $scope.setIndex = function(index) {
  40. $scope.$slideIndex = index;
  41. };
  42. }];
  43. app.directive('bzSlider', ['$timeout', '$parse', function ($timeout, $parse) {
  44. return {
  45. restrict: 'AC',
  46. replace: false,
  47. scope: true,
  48. controller: bzSliderController,
  49. link: function(scope, element, attrs) {
  50. element.addClass('bz-slider');
  51. scope.$slideIndex = 0;
  52. scope.$slides = [];
  53. // watch for slides update
  54. scope.$watch(attrs.bzSlider, function(value) {
  55. var arr = [];
  56. angular.forEach(element.children(), function(item) {
  57. if (angular.element(item).hasClass('bz-slide')) {
  58. arr.push(item);
  59. }
  60. });
  61. scope.$slides = arr;
  62. });
  63. // delay
  64. if (angular.isDefined(attrs.delay)) {
  65. scope.$watch(attrs.delay, function(value) {
  66. scope.$delay = value;
  67. });
  68. }
  69. // autoplay
  70. if (angular.isDefined(attrs.autoplay)) {
  71. scope.$autoplay = $parse(attrs.autoplay)(scope);
  72. if (scope.$autoplay) {
  73. scope.play();
  74. }
  75. }
  76. }
  77. };
  78. }]);
  79. return app;
  80. }));