Skip to content

Instantly share code, notes, and snippets.

Created February 4, 2015 00:00
Show Gist options
  • Save anonymous/56cb4ec8afe2d59c848e to your computer and use it in GitHub Desktop.
Save anonymous/56cb4ec8afe2d59c848e to your computer and use it in GitHub Desktop.
Angular Event Example
angular.module('app', []);
angular.module('app').controller('HomeController', HomeController);
angular.module('app').controller('SubController', SubController);
HomeController.$inject = ['$scope', '$rootScope'];
SubController.$inject = ['$scope'];
function HomeController($scope, $rootScope) {
$scope.$on('globalEvent', runGlobalLog);
$scope.$on('childEvent', runChildLog);
this.triggerGlobal = triggerGlobal;
this.triggerSub = triggerSub;
function triggerGlobal () {
$rootScope.$broadcast('globalEvent', { key: 1 });
};
function triggerSub () {
$scope.$broadcast('parentEvent', 'Martin');
};
function runGlobalLog(event, data) {
alert(data.key);
};
function runChildLog(event, data) {
alert(data.key);
};
};
function SubController($scope) {
var vm = this;
$scope.$on('parentEvent', setSubtext);
$scope.$on('globalEvent', setSubtext);
this.triggerParent = triggerParent;
function setSubtext(event, data) {
if (typeof data == 'object') {
vm.subtext = data.key;
} else {
vm.subtext = data;
}
};
function triggerParent () {
$scope.$emit('childEvent', { key: 2 });
};
};
<html>
<head>
<title>Angular Event Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script type="text/javascript" src="controllers.js"></script>
</head>
<body ng-app="app">
<div ng-controller="HomeController as home">
<button ng-click="home.triggerGlobal()">Trigger!</button>
<button ng-click="home.triggerSub()">Trigger Sub!</button>
<div ng-controller="SubController as sub">
<span ng-bind="sub.subtext"></span>
<button ng-click="sub.triggerParent()">Trigger Parent!</button>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment