Alias
Alias

Reputation: 3091

$broadcast not being picked up in directive

I've got 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'});
        }
    };
}]);

In my controller, I simply call the hello method: User.hello(), which logs my console message.

I'd like to pick this up in a directive, but it doesn't seem to work...

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);
            });
        }]
    }
}]);

Nothing is logged... I've tried wrapping the broadcast in a timeout to make sure the directive is loaded but no joy. Also tried $emit instead of $broadcast.

My HTML is like so:

<body>
    <div ng-controller="myController">
        <!-- Used to execute service -->
    </div>
    <user></user>
</body>

Upvotes: 0

Views: 563

Answers (2)

CDelaney
CDelaney

Reputation: 1248

Link should be a function, shouldn't it? Rather than an array, since its parameters are static.

link: function(scope, element, attrs) {

    scope.$on('saidhello', function(event, data) {
        console.log('User said ' + data.greeting);
    });

    // say hello
    User.hello();
}

http://plnkr.co/edit/Shj112rfu6dyTcUHPVfM?p=preview

Upvotes: 2

charlietfl
charlietfl

Reputation: 171698

The issue boils down to the fact that controllers must run before the DOM can be compiled in order to create scope needed for the view.

By calling an event immediately in controller you are calling it before the listener in directive has been attached.

By the time listener has been attached the event is already over

Upvotes: 0

Related Questions