AngularJS Example

by tomascot

HTML

<div ng-app="zippyModule">
  <div ng-controller="Ctrl3">
    Title: <input ng-model="title"> <br>
    Text: <textarea ng-model="text"></textarea>
    <hr>
    <div class="zippy" zippy-title="Details: {{title}}...">{{text}}</div>
  </div>
</div>

CSS

</style> <!-- Ugly Hack to make remote files preload in jsFiddle --> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<style>.zippy {
  border: 1px solid black;
  display: inline-block;
  width: 250px;
}
.zippy.opened > .title:before { content: '▼ '; }
.zippy.opened > .body { display: block; }
.zippy.closed > .title:before { content: '► '; }
.zippy.closed > .body { display: none; }
.zippy > .title {
  background-color: black;
  color: white;
  padding: .1em .3em;
  cursor: pointer;
}
.zippy > .body {
  padding: .1em .3em;
}

JavaScript

function Ctrl3($scope) {
  $scope.title = 'Lorem Ipsum';
  $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}

angular.module('zippyModule', [])
  .directive('zippy', function(){
    return {
      restrict: 'C',
      // This HTML will replace the zippy directive.
      replace: true,
      transclude: true,
      scope: { title:'@zippyTitle' },
      template: '<div>' +
        '<div class="title">{{title}}{{col}}</div>' +
                  '<div class="body" ng-transclude></div>' +
                '</div>',
      // The linking function will add behavior to the template
      link: function(scope, element, attrs) {
            // Title element
        var title = angular.element(element.children()[0]),
            // Opened / closed state
            opened = true;
        var col = 50;

        // Clicking on title should open/close the zippy
        title.on('click', toggle);

        // Toggle the closed/opened state
        function toggle() {
          opened = !opened;
          element.removeClass(opened ? 'closed' : 'opened');
          element.addClass(opened ? 'opened' : 'closed');
        }

        // initialize the zippy
        toggle();
      }
    }
  });