加载特定的ng-view时如何连接每个tym的socket?卸货时摧毁?

时间:2013-10-15 12:50:49

标签: node.js angularjs socket.io

我正在尝试使用angular socket.io和nodejs构建一个Web应用程序。当在ng-view上加载特定模板时,是否可以连接到每个tym的服务器套接字?我试过几次。它只在第一次工作。当我加载另一个视图并回到旧视图时我必须刷新页面,否则它不起作用! 谢谢你提前! 服务器端代码:

io.on("connection", function(socket){
  Events.find().exec(function(err,existing_events){    
      if(err)
      {
          console.log(err);
          socket.emit('err',{message: "events can not be loaded now!"})
      }
      else
      {
        socket.emit('events',{events: existing_events});
      }
    });
}

这是客户端代码: 角度配置:

window.app.config(['$routeProvider', '$locationProvider',
    function($routeProvider,$locationProvider) {
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');
        $routeProvider.
        when('/event', {
            templateUrl: '/views/eventsHome.html'            


        }).
        when('/', {
            templateUrl: 'views/index.html'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);

eventsHome.html:

<div ng-controller="eventsCtrl">
  <label style="width:15%;float:left;">Current Events</label>
  <a style="float:left;" href="" id="create" ng-click="create()">Create Event</a>
  <div style="border:none; width:90%; max-height:200px; overflow:auto;overflow-x:hidden; clear:both; padding-left:2%; margin-top:5%;">


    <div id='events' ng-repeat="event in events">
            <a href="/event/{{event.name}}" ng-click="leave()">{{event.name}}</a>

    </div>
  </div>


</div>

eventsCtrl:

angular.module('myApp.system').controller('eventsCtrl', ['$scope', 'Global','$location', function ($scope, Global,$location) {
      var socket;
      var sessionId = '';
      var serverBaseUrl = document.domain;
      socket = io.connect(serverBaseUrl);
      $scope.events;
      socket.on('connect', function () {
        sessionId = socket.socket.sessionid;
        console.log('Connected ' + sessionId);
        //socket.emit('newUser', {id: sessionId, name: user_name});
      });
      socket.on('events',function(data){
        //updateEvents(data.events);
        $scope.$apply(function () {
          // body...
          $scope.events=data.events;
        });

      });

 }]);

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是做你想要的(假设我正确理解),就是使用$route服务来监听视图的变化。可以在Angular Docs中找到所有可用$routeChange个事件的文档。以下是如何监听路线变化的示例:

'eventsCtrl'控制器中:

.controller('eventsCtrl', ['$scope','$rootScope', ... // and other dependencies
    function($scope, $rootScope, ...){
        ...
        $rootScope.$on('$routeChangeSuccess', function(e, currRoute, prevRoute){
            switch(currRoute){
                // test for which specific routes you want to check for
                // such as connecting to or destroying your various sockets
            }
        });
        ...
    }
]);

每次路线发生变化时,都会通知$rootScope并告诉您路线改变的路线。希望这能满足您的需求。