0

I have a controller defined as follows:

menuController.controller('menuController', ['$scope', '$rootScope', '$log', 'techMessageService', 'subscriptionService',
function ($scope, $rootScope, $log, techMessageService, subscriptionService) {
    $scope.newTechMessage = false;
    var handleNewTechMessage = function (data) {
        $log.log('handleTechMessage: ' + data);
        $scope.newTechMessage = true;
    };

    var init = function () {
        $log.log('menuController init');

        subscriptionService.subscribeTechMessages(handleNewTechMessage);
    };

    init();
}]);

subscriptionService is like:

subscriptionService.service('subscriptionService', ['$log', 'backendService', function  ($log, backendService) {
this.subscribeTechMessages = function (handler) {
    $log.log('subscriptionService:subscribeTechMessages');

    var socket = io.connect('https://localhost:9001');

    socket.on('connect', function () {
        socket.emit('adduser', '80040002');
    });

    backendService.post('/subscribeTechMessages');

    socket.on('NEW_MESSAGE', handler);
};

this.unsubscribeTechMessages = function () {
    $log.log('subscriptionService:unsubscribeTechMessages');
    return backendService.post('/unsubscribeTechMessages');
};
}]);

The problem I have is the handleNewTechMessage function which is passed to the service. It is executed as an event handler, it sets newTechMessage scope variable to true but the change is not reflected on the view. I have newTechMessage bind on the view and it is still false. What do I misunderstand? I suppose it should work but I wonder if that function passing is all right when modifying scope variables.

1 Answer 1

2

Call digestion

In the handleNewTechMessage callback, call a scope digestion with $scope.$apply(). Without this digestion call, there is no reason Angular should understand something may have changed.

Callbacks as an array

In your implementation, each handler registration makes a call to io.connect. Better have an internal array the callbacks are pushed in, and looped in on socket message.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it. Thank you. As far as call to io.connect you are right. That's early implementation which is going to be changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.