-
-
Save martin-brennan/3afbc66e144d13f19c56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }); | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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