AngularJS: listen to multiple events with $on
by Brian
HTML
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css">
<div ng-app="MyApp">
<div ng-controller="myCtrl">
<button class="btn" ng-click="one()">One</button>
<button class="btn" ng-click="two()">Two</button>
<button class="btn" ng-click="three()">Three</button>
</div>
</div>
CSS
body{padding:20px}
JavaScript
var MyApp = angular.module('MyApp',[]);
MyApp.controller('myCtrl',function($scope){
angular.forEach(['one','two','three'], function(value){
$scope.$on(value, function(event){
console.log(event.name);
});
});
$scope.one = function(){
$scope.$emit('one');
console.log('1');
};
$scope.two = function(){
$scope.$emit('two');
console.log('2');
};
$scope.three = function(){
$scope.$emit('three');
console.log('3');
};
});