I am working with a simple service/factory:
angular.module('myapp').factory('User', ['$rootScope', function($rootScope) {
return {
hello: function() {
console.log('Sending root scope message');
$rootScope.$broadcast('saidhello', {greeting: 'hey'});
}
};
}]);
Within my controller, I am calling the hello method simply like this: User.hello()
, and it logs the message in my console.
Now, I want to capture this event in a directive, but for some reason, it doesn't seem to be working...
angular.module('myapp').directive('user', ['User', function(User) {
return {
replace: true,
restrict: 'EA',
scope: true,
link: ['scope', 'element', 'attrs', function(scope, element, attrs) {
scope.$on('saidhello', function(event, data) {
console.log('User said ' + data.greeting);
});
}]
}
}]);
Despite my efforts, nothing is being logged. I even tried using timeout to ensure that the directive is loaded, but still no luck. I also attempted to use $emit
instead of $broadcast
.
The structure of my HTML looks like this:
<body>
<div ng-controller="myController">
<!-- Used to execute service -->
</div>
<user></user>
</body>