AngularJS e le direttive - pt3: final

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-accordion data="ctrl.panels"></xyz-accordion>
</div>


<!-- xyzAccordtion directive template -->
<script type="text/ng-template" id="templates/accordion.tpl.html">
    <xyz-panel item="p" ng-repeat="p in data"></xyz-panel>
</script>


<!-- 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.panels = [
		{title: 'Valentino Rossi', content: "Entra nel mondiale nel 1996 ed è su..."},
		{title: 'Jorge Lorenzo', content: "Inizia la sua carriera mondiale nel 2002 ..."},
		{title: 'Marc Marchez', content: "È il talento piú straodinario del panorama ..."},
	];

})        


        
// Accordion directive
.directive ('xyzAccordion', function () {

	return {
		restrict: 'E',
		scope: {
			data: '='
		},
		templateUrl: 'templates/accordion.tpl.html',

	    controller: function ctrl($scope) {

			this.closeAll = function (){
				angular.forEach($scope.data, function(value, key){
					value.opened = false;
				});

			}
		}
	};

})


// Panel Directive
.directive ('xyzPanel', function () {

	return {
		restrict: 'E',
		require: '?^xyzAccordion',
		scope: {
			item: '='
		},
		templateUrl: 'templates/panel.tpl.html',

		link: function(scope, el, attrs, ctrl) {
			
			// Close panel by default
			// scope.item.opened = false;

			scope.toggle = function (){
				
				// Close all panels (only if inside an accordion)
				if (ctrl) { ctrl.closeAll(); }

				// Toggle Visibility
				scope.item.opened = !scope.item.opened;
			}
		}
	};

});