You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.6 KiB
2.6 KiB
AngularJS - Events
Lesson Objectives
- Describe situations where communicating between controllers is difficult
- Send and receive an event
Describe situations where communicating between controllers is difficult
- We want to modularize our code, so that when a controller performs an action, it can notify all of its ancestors/descendants
- This allows a developer to work on his/her specific module, without worrying about what's going on around them
- When elements with controllers are being created dynamically, knowing a controller's ancestors/descendants can become difficult.
Send and receive an event
To send a message down to your descendant controllers:
$scope.$broadcast('eventName', { message: msg });
To send a message up to your ancestor controllers:
$scope.$emit('eventName', { message: msg });
To receive a message sent by another controller:
$scope.$on('eventName', function (event, data) {
//do stuff here
});
Examples
Broadcast
file: index.html
<!DOCTYPE html>
<html >
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js'></script>
<script src="js/app.js"></script>
</head>
<body>
<main ng-app="MyApp">
<h1>Hi</h1>
<section ng-controller="ParentCtrl as parent">
<a href="#" ng-click="parent.sendMessage()">Click to Send Message</a>
<div ng-controller="ChildCtrl as child"></div>
</section>
</main>
</body>
</html>
file: js/app.js
const app = angular.module('MyApp', []);
app.controller('ParentCtrl', ['$scope', function($scope){
this.sendMessage = function(){
$scope.$broadcast('eventName', { someProperty:'somevalue' });
}
}]);
app.controller('ChildCtrl', ['$scope', function($scope){
$scope.$on('eventName', function(event, data){
console.log(data);
});
}]);
Emit
file: index.html
<!DOCTYPE html>
<html >
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js'></script>
<script src="js/app.js"></script>
</head>
<body>
<main ng-app="MyApp">
<h1>Hi</h1>
<section ng-controller="ParentCtrl as parent">
<div ng-controller="ChildCtrl as child">
<a href="#" ng-click="child.sendMessage()">Click Me</a>
</div>
</section>
</main>
</body>
</html>
file: js/app.js
const app = angular.module('MyApp', []);
app.controller('ParentCtrl', ['$scope', function($scope){
$scope.$on('eventName', function(event, data){
console.log(data);
});
}]);
app.controller('ChildCtrl', ['$scope', function($scope){
this.sendMessage = function(){
$scope.$emit('eventName', { someProperty:'somevalue' });
}
}]);