Call controller function from service in angularjs

前端 未结 3 1878

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:48

    I know this is an old question, but I have another option. I have a personal bias against $broadcast - it just doesn't feel very 'angularish', I prefer making explicit calls in my code.

    So instead of broadcasting to the controller and triggering another digest cycle, I prefer to have the controller register itself to the service, as below. Just be careful not to introduce any circular dependencies if the controller makes use of the same service. This works best with the controllerAs syntax, so that the calling service does not need to care about $scope.

    Yes, this is more code than $broadcast, but it does give the service total access to the entire controller - all of it's methods and properties.

    .service('SocketService', function ($http,$rootScope,$q) {
      var _this = this;    
      this.chatController = null;
      this.registerCtrlr = function (ctrlr) {
        _this.chatController = ctrlr;
      };
      this.unRegisterCtrlr = function () {
        _this.chatController = null;
      };
    
      this.connect = function(){
        var socket = io();
        socket.on('connect',function(){
          // Call chatController.someFunction if chatController exists
          if (_this.chatController) {
            _this.chatController.someFunction();
          }
        });
      };
    });
    
    .controller('ChatController',['SocketService', '$scope', function(SocketService, $scope){
      SocketService.registerCtrlr(this);
      //-- make sure controller unregisters itself when destroyed - need $scope for this
      $scope.$on('$destroy', function () {
        SocketService.unRegisterCtrlr();
      });
      this.someFunction = function(){
        // Some Code Here
      }
    }]);
    

提交回复
热议问题