Skip to content

Instantly share code, notes, and snippets.

@joerx
Created March 23, 2015 05:15
Show Gist options
  • Save joerx/61213cb693c9f1cf446f to your computer and use it in GitHub Desktop.
Save joerx/61213cb693c9f1cf446f to your computer and use it in GitHub Desktop.
Angular events
<!DOCTYPE html>
<html class="no-js" ng-app="myApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>sp-directives</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body >
<div ng-controller="oneController">
<button type="button" ng-click="emitEvent()">Click Me!</button>
</div>
<div ng-controller="twoController">
<p>{{info.message}}</p>
</div>
<div ng-controller="threeController">
</div>
<script type="text/javascript">
(function() {
var app = angular.module('myApp', []);
app.controller('oneController', function($scope) {
var counter = 0;
$scope.emitEvent = function() {
console.log('click!');
counter += 1;
$scope.$emit('buttonClick', {count: counter});
}
});
app.controller('twoController', function($scope, $rootScope) {
$scope.info = {
message: 'Nothing happened yet'
}
$rootScope.$on('buttonClick', function(evt, data) {
console.log('was clicked!');
console.log(arguments);
$scope.info.message = 'Button was clicked ' + data.count + ' time(s)';
});
});
app.controller('threeController', function($scope, $rootScope) {
$scope.$on('buttonClick', function() {
console.log('click received on controller scope');
});
$rootScope.$on('buttonClick', function() {
console.log('click received on root scope');
});
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment