AngularJS - Using events to communicate between controllers & directives
by vacationlabs
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<div ng-app="MyModule" keyboard-shortcuts="">
Press + to create a new block.
<div ng-controller="BlockGroupController">
<div ng-repeat="group in groups" class="group">
Group #{{ group}}
<div ng-controller="BlockController">
<div ng-repeat="block in blocks" class="block">
Block #{{ block }}
</div>
</div>
</div>
</div>
</div>
JavaScript
var mod = angular.module('MyModule', []);
mod.controller('BlockGroupController', ['$scope', function($scope) {
$scope.groups=[1];
$scope.$on('keypress', function(evt, char) {
$scope.groups.push($scope.groups.length);
});
}]);
mod.controller('BlockController', ['$scope', function($scope) {
$scope.blocks=[1];
$scope.$on('keypress', function(evt, char) {
$scope.blocks.push($scope.blocks.length);
});
}]);
mod.directive('keyboardShortcuts', function() {
return {
'restrict' : 'A',
'link' : function(scope, element, attrs) {
console.log('called outside', element);
element.keyup(function(evt) {
console.log('called');
if(evt.which==43) {
scope.$apply(function() {
scope.$broadcast('keypress', '+');
});
}
});
}
}
});