Angular: One Controller for Multiple Directives
http://angularjs.org/
by Jeanette Head
HTML
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<super-directive current-item="{name: 'Superman', alias: 'Clark Kent'}" all-items="[{name: 'Superman', alias: 'Clark Kent'}, {name: 'Spiderman', alias: 'Peter Parker'}, {name: 'Wonder Woman', alias: 'Diana Prince'}, {name: 'Black Widow', alias: 'Natasha Romanova'}]"></super-directive>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.min.js"></script>
<style>
h3 {
cursor: pointer;
}
li {
cursor: pointer;
font-size: 24px;
}
JavaScript
var myApp = angular.module('myApp',[]);
myApp
.directive('superDirective', superDirective)
.directive('minimizedDirective', minimizedDirective)
.directive('detailDirective', detailDirective)
.directive('listDirective', listDirective)
.controller('SuperController', function ($scope) {
$scope.VIEW_STATES = {minimized: 1, detail: 2, list: 3};
$scope.viewState = $scope.VIEW_STATES.minimized;
$scope.showDetail = function() {
$scope.viewState = $scope.VIEW_STATES.detail;
}
$scope.showList = function() {
$scope.viewState = $scope.VIEW_STATES.list;
}
$scope.selectItem = function(item) {
$scope.currentItem = item;
$scope.viewState = $scope.VIEW_STATES.minimized;
}
});
function superDirective() {
return {
restrict: 'EA',
template: '<minimized-directive ng-show="viewState === VIEW_STATES.minimized" ng-click="showDetail()"></minimized-directive><detail-directive ng-show="viewState === VIEW_STATES.detail" ng-click="showList()"></detail-directive><list-directive ng-show="viewState === VIEW_STATES.list" ng-click="showMinimized()"></list-directive>',
controller: 'SuperController',
scope: {
currentItem: '=',
allItems: '='
}
};
}
function minimizedDirective() {
return {
restrict: 'EA',
template: '<h3>{{currentItem.name}}</h3><h5>(Click name to see details)</h5>',
controller: 'SuperController'
};
}
function detailDirective() {
return {
restrict: 'EA',
template: '<h3><label>Name:</label> {{currentItem.name}}, <label>Alias:</label> {{currentItem.alias}}</h3><h5>(Click name to see all superheros)</h5>',
controller: 'SuperController'
};
}
function listDirective() {
return {
restrict: 'EA',
template: '<ul><li ng-repeat="item in allItems" ng-click="selectItem(item)"<h3><label>Name:</label> {{item.name}},...