Skip to content

Instantly share code, notes, and snippets.

@ShawInnes
Last active August 29, 2015 14:19
Show Gist options
  • Save ShawInnes/efe5ea694cc16303e8b1 to your computer and use it in GitHub Desktop.
Save ShawInnes/efe5ea694cc16303e8b1 to your computer and use it in GitHub Desktop.
//// define this on the app module
.factory('notify', ['$rootScope', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
}])
///// do this on the publishing controller
.controller( 'AppCtrl', ['$scope', '$location', 'notify', function AppCtrl ( $scope, $location, notify ) {
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if ( angular.isDefined( toState.data.pageTitle ) ) {
$scope.pageTitle = toState.data.pageTitle + ' | ngBoilerplate' ;
}
});
$scope.onKeyPress = function ($event) {
if ($event.keyCode === 49) {
$location.path('home');
}
else if ($event.keyCode === 50) {
$location.path('about');
}
else if ($event.keyCode === 51) {
$location.path('admin');
}
else if ($event.keyCode === 52) {
notify.prepForBroadcast('add ' + Date.now());
}
};
}]);
///// register this on the subscribing controller
.controller( 'HomeCtrl', ['$scope', function HomeController( $scope ) {
$scope.$on('handleBroadcast', function() {
console.log('got a message on HomeCtrl');
});
}]);
//// or to get the value
.controller( 'HomeCtrl', ['$scope', 'notify', function HomeController( $scope, notify ) {
$scope.items = [ ];
$scope.$on('handleBroadcast', function() {
$scope.items.push(notify.message);
});
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment