从 angularjs 中的服务调用控制器功能 [英] Call controller function from service in angularjs

查看:34
本文介绍了从 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();
    })
});

希望能帮到你,谢谢.

这篇关于从 angularjs 中的服务调用控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆