SMSk
SMSk

Reputation: 705

Problems with $broadcast in angular

I have a service, AuthenticationService and a controller HeaderCtrl. When the user is logged on, my server sends me his first and last name, which I change in my service and broadcast it. Then I want to use it in my controller. However, $on is apparently never called.

Service code:

service.setName = function(first_name, last_name){
    service.firstName = first_name;
    service.lastName = last_name;
    $rootScope.$broadcast('nameChanged');
    console.log('wtf');
};

Controller code:

angular.module('app')
    .controller('HeaderCtrl', ['$scope', '$location', 'AuthenticationService', function ($scope, $location, AuthenticationService) {

        $scope.$on('nameChanged', function(){
            console.log('ftw');
            $scope.firstName = AuthenticationService.firstName;
            $scope.lastName = AuthenticationService.lastName;
        });
    }]);

I can see wtf in console, and cannot see ftw. What am I doing wrong?

Upvotes: 1

Views: 89

Answers (2)

tomastrajan
tomastrajan

Reputation: 1726

Why not just inject the service into controller and bind to the data in service directly. With that you elminate need for manual synchronziation using events. Actualy you are doing it already but only after you trigger the event.

If you store those properties on object like AuthenticationService.user.firstName then you can bind it to controller in the begining like: $scope.user = AuthenticationService.user and you will get automaticaly synchronzied data for free.

Upvotes: 0

potatopeelings
potatopeelings

Reputation: 41075

You might want to check if the controller is already instantiated when you are broadcasting (add a console.log on the first line of the controller).

Otherwise the controller misses the broadcast because it turns on it's listener after the broadcast is over.

Upvotes: 2

Related Questions