Angular Cats! Part 5 – Custom Directive

One more thing…

I took the liberty of making a custom directive out of the Twitter Bootstrap Carousel widget. You’ll see it in partials/catDeatil.html as . I’m not 100% certain I’m doing things the ‘correct angular way’, but it seems to work.

Demo | Code

The catCarousel.html partial:

<!-- The ngCarousel directive gets inserted here to fix a timing error between angularjs and bootstrap -->
<div id="myCarousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <!-- Give the first item in the collection the 'active' class -->
    <div ng-class="{item:true, active:$first}" ng-repeat="photo in pics">
      <img ng-src="{{photo}}">
  <!-- Carousel Arrow Buttons -->
  <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a>
  <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a>

The directive code:

The templateURL property specifies the HTML to insert into the directive tag. I’ve restricted the type of directive to an element name. It’s just easy that way. One caveat though, it that special considerations need to be made for this to be IE7/8 compatable.

The link function will take the value of the ‘pics’ attribute in the catcarousel HTML tag and assign it to the directive scope. Whenever the ‘cat’ object changes – either by clicking Next/Prev, or selecting a cat from the grid – the directive will update the ‘pics’ and call the carousel() function on the root element of the directive template.

angular.module('myDirectives', [])
.directive('catcarousel', function(){
  return {
    templateUrl: 'partials/catCarousel.html',
    restrict: 'EAC',
    link: function (scope,element,attr) {
      scope.$watch('cat', function () { = scope.$eval(;
          interval: 0

And that just about wraps it up. There’s plenty more code in the cat apps than outlined in these blog posts, so if anyone is interested, please take a look at the project on GitHub. I tried to add as many useful comments as I could. If any Angular experts run across this and are horrified by any of the code, please let me know! Thanks. Bye.

1 Comment

  1. Hi,
    I’m new to ng and was looking for a carousel that works with-in its scope – … I’ve started studying your code but it would be gr8 if you could put up an example of it as an independent component.

    Many thanks!

Leave a Reply

Your email address will not be published.


© 2018 Eric Terpstra

Theme by Anders NorénUp ↑