Last active
December 31, 2015 17:59
-
-
Save jskrepnek/8024016 to your computer and use it in GitHub Desktop.
AngularJS text carousel directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
I really like to <span text-carousel values="run, walk, bike, jog, eat, sleep, and drink"></span>. | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive('textCarousel', function ($timeout) { | |
return { | |
restrict: 'A', | |
link: function (scope, elem, attrs) { | |
var timeoutId, | |
index = 0, | |
values; | |
values = attrs.values.split(','); | |
function goToNextValue() { | |
index += 1; | |
if (index >= values.length) { | |
index = 0; | |
} | |
}; | |
function setCarouselText() { | |
elem.text(values[index]); | |
} | |
function updateCarousel() { | |
setCarouselText(); | |
goToNextValue(); | |
scheduleNext(); | |
}; | |
function scheduleNext() { | |
timeoutId = $timeout(function () { | |
elem.fadeOut(200, function () { | |
$(this).text(values[index]).fadeIn(20); | |
updateCarousel(); | |
}); | |
}, 2000); | |
}; | |
updateCarousel(); | |
elem.on('$destroy', function () { | |
$timeout.cancel(timeoutId); | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment