Mastering Web Application

(Rick Simeone) #1

Angular Zen


Hierarchy of scopes and the eventing system


Scopes organized in a hierarchy can be used as an event bus. AngularJS allows us
to propagate named events with a payload through the scopes' hierarchy. An event
can be dispatched starting from any scope and travel either upwards ($emit) or
downwards ($broadcast).


$rootscope

$scope.$broadcast()‘down’
$scope.$emit(‘up’)

AngularJS core services and directives make use of this event bus to signal
important changes in the application's state. For example, we can listen to the
$locationChangeSuccess event (broadcasted from the $rootScope instance)
to be notified whenever a location (URL in a browser) changes, as given in the
following code:


$scope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl){

//react on the location change here
//for example, update breadcrumbs based on the newUrl

});

The $on method available on each scope instance can be invoked to register
a scope-event handler. A function acting as a handler will be invoked with
a dispatched event object as its first argument. Subsequent arguments will
correspond to the event's payload and are event-type dependent.


Similar to the DOM events, we can call the preventDefault() and
stopPropagation() methods on event object. The stopPropagation() method
call will prevent an event from bubbling up the scopes' hierarchy, and is available
only for events dispatched upwards in the hierarchy ($emit).

Free download pdf