从 angularjs 中的服务调用控制器功能

从 angularjs 中的服务调用控制器功能

问题描述:

我正在使用 socket.io 在我的应用程序中启用聊天,我正在使用服务 SocketService 来执行所有套接字内容.当消息到来时,我想从服务 SocketService 触发控制器的功能,以在 UI 中进行一些更改.所以我想知道如何从服务访问控制器的功能.示例代码:

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'
    });
  }
});

这是服务的示例代码.

现在是控制器的代码

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

您可以通过使用角度事件 $broadcast$emit 来实现这一点.

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

在您的情况下 $broadcast 会有所帮助,您需要在 $rootscope 中广播您的事件,该事件可以被具有相同事件名称的 $on 的所有子作用域监听.

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.

代码

.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();
    })
});

希望能帮到你,谢谢.