$broadcast to current scope

余生长醉 提交于 2020-01-04 02:48:27

问题


To preface, I have an Ionic app connected to a Node server via a websocket and the Node server is connected to a C++ app via a TCP socket. I have this service that connects and serves up the socket but also watches for a nack response so that it can issue an alert notifying the user of the error:

(function(){
  'use strict';

  angular.module('tacoCorp.services')
    .factory('Socket', Socket);

  Socket.$inject = ['socketFactory', 'OSDP', '$rootScope'];

  function Socket(socketFactory, OSDP, $rootScope) {
    var socket = io('localhost:3000');

    socket = socketFactory({ioSocket: socket});

    socket.on('connect', function() {
        console.log('connected');
    });

    socket.on('nack', function(data) {
        console.log(data);
        var error = OSDP.parse(data);
        $rootScope.$broadcast('nack', error);
    });

    return socket;
  }
}());

I have this in each controller listening so that it can issue the popup:

$scope.$on('nack', function(e, err) {
        console.log(err);
        var alertPopup = $ionicPopup.alert({
            title: 'Error',
            template: err.error
        });
    });

My problem is that it is firing multiple times even though my there is only one controller for each state/view. Almost as if $destroy isn't happening or it's not removing the listener. Still happens if I do this:

var nackListener = $scope.$on('nack', function(e, err) {
        console.log(e);
        var alertPopup = $ionicPopup.alert({
            title: 'Error',
            template: err.error
        });
    });

    $scope.$on('$destroy', nackListener);

I'm not sure what the best way to handle this is.


回答1:


As Radim Köhler pointed out $ionicConfigProvider.views.maxCache(0) fixes this issue where cache:false on the state does not. You could also do this:

$scope.$on("$ionicView.afterLeave", function () {
        $ionicHistory.clearCache();
    });

Best way for me is to just pick one controller to put it on and be done with it.



来源:https://stackoverflow.com/questions/35076821/broadcast-to-current-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!