我正在尝试使用 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>
事件控制:
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;
});
});
}]);