Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am using socket.io to enable chat in my app and i am using a service SocketService to perform all the socket stuff. When a message came then i want to trigger a function of a controller from the service SocketService to make some changes in the UI. So i want to know that how can i access the function of a controller from the service. Sample Code:

.service('SocketService', function ($http,$rootScope,$q) {
  this.connect = function(){
    var socket = io();
    socket.on('connect',function(){
      // Call a function named 'someFunction' in controller 'ChatController'
    });
  }
});

This is the sample code for service.

Now the code for controller

.controller('ChatController',function('SocketService',$scope){
  $scope.someFunction = function(){
     // Some Code Here
  }
});
share|improve this question
up vote 19 down vote accepted

You could achieve this by using angular events $broadcast or $emit.

In your case $broadcast would be helpful, You need to broadcast your event in $rootscope that can be listen by all the child scopes which has $on with same event name.

CODE

.service('SocketService', function($http, $rootScope, $q) {
    this.connect = function() {
        var socket = io();
        socket.on('connect', function() {
            // Call a function named 'someFunction' in controller 'ChatController'
            $rootScope.$broadcast('eventFired', {
                data: 'something'
            });
        });
    }
});


.controller('ChatController', function('SocketService', $scope) {
    $scope.someFunction = function() {
        // Some Code Here
    }
    $scope.$on('eventFired', function(event, data) {
        $scope.someFunction();
    })
});

Hope this could help you, Thanks.

share|improve this answer
    
Thanks @pankajparkar $broadcast worked here perfectly. – Vinit Chouhan Mar 5 '15 at 18:38
    
@VinitChouhan cool, Glad to help you, Thanks :) Happy Coding – Pankaj Parkar Mar 5 '15 at 18:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.