AngularJS e le direttive - pt1: collapsable panel

by Fabio Biondi

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-controller="AppCtrl as ctrl" class="jumbotron">
  <xyz-panel item="ctrl.myStaticPanel1"></xyz-panel>
  <xyz-panel item="ctrl.myStaticPanel2"></xyz-panel>
  <xyz-panel item="ctrl.myStaticPanel3"></xyz-panel>
</div>


<!-- xyzPanel directive template -->
<script type="text/ng-template" id="templates/panel.tpl.html">
  <div class="panel panel-default" >
    <div class="panel-heading" ng-click="toggle(); ">{{item.title}} </div>
    <div class="panel-body" ng-show="item.opened">{{item.content}}</div>
  </div>
</script>

JavaScript

var app = angular.module('myApp', [])

// Main controller
.controller('AppCtrl', function(){
	this.myStaticPanel1 = {title: 'Panel 1', content: 'body'};
	this.myStaticPanel2 = {title: 'Panel 2', content: 'another body'};
	this.myStaticPanel3 = {title: 'Panel 3', content: 'another content'};
})        


// Panel Directive
.directive ('xyzPanel', function () {
	return {
		restrict: 'E',
		scope: {
			item: '='
		},
		templateUrl: 'templates/panel.tpl.html',

		link: function(scope, el, attrs) {
			
			scope.item.opened = false;

			scope.toggle = function (){
				scope.item.opened = !scope.item.opened;
			}
		}
	};
});