user554180
user554180

Reputation:

Angularjs $on not firing after $rootScope.$broadcast

I have this code where two controllers are using a shared service to communicate.

var app = angular.module('AdminApp', ['ngRoute']);

app.factory('SharedService', function ($rootScope) {

    var sharedService = {

        userId: [],

        BroadcastUserId: function (id) {
            this.userId.push(id);
            $rootScope.$broadcast('handleBroadcast');
        }
    };
    return sharedService;
});

app.config(function ($routeProvider) {

    $routeProvider.when('/login', {
        templateUrl: "adminLogin.html"
    });

    $routeProvider.when('/main', {
        templateUrl: 'adminMain.html'
    });

    $routeProvider.otherwise({
        redirectTo: '/login'
    });
});

app.controller('authCtrl', function ($scope, $http, $location, SharedService) {

    $scope.Userid = '';
    $scope.authenticate = function (user, pass) {
        $http.post('http://localhost/NancyAPI/auth', {
            UserName: user,
            Password: pass
        }).success(function (data) {
            $scope.$broadcast('Token', data.Token);
            $http.defaults.headers.common['Authorization'] = 'Token ' + data.Token;
            $scope.Userid = data.UserId;
            SharedService.BroadcastUserId($scope.Userid);
            $location.path("/main");
        }).error(function (response) {
            $scope.authenticationError = response.error || response;
        });
    };

    $scope.$on('handleBroadcast', function () {
        console.log('on');
    });
}).$inject = ['$scope', '$rootScope', 'SharedService'];

app.controller('mainCtrl', function ($scope, $http, $q, SharedService) {

    $scope.tests = [];
    $scope.userId = -1;

    $scope.getTests = function () {
        var deferred = $q.defer();
        $http.get('http://localhost/NancyAPI/auth/tests/' + $scope.userId).
            success(function (data) {
                deferred.resolve(data);
                $scope.tests = angular.fromJson(data);
            }).error(function (response) {
            });
    };

    // THIS IS NOT FIRING
    $scope.$on('handleBroadcast', function () {
        $scope.userId = SharedService.userId;
    });
}).$inject = ['$scope', '$rootScope', 'SharedService'];

For some reason the $scope.$on is firing in the AuthCtrl controller but not in the mainCtrl.

// THIS IS NOT FIRING
        $scope.$on('handleBroadcast', function () {
            $scope.userId = SharedService.userId;
        });

Why is this happening and how do I fix it?

Upvotes: 1

Views: 3638

Answers (1)

Tyagi Akhilesh
Tyagi Akhilesh

Reputation: 860

I made a subtle mistake of not providing the {$rootScope} as dependency. Once I corrected that, it worked for me. I used Inline Array Annotation mechanism to achieve the same.

Upvotes: 3

Related Questions