Call controller function from service in angularjs

前端 未结 3 1877

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

3条回答
  •  一向
    一向 (楼主)
    2020-12-31 07:50

    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.

提交回复
热议问题