Angularjs Socket.io和$scope.$apply()
我正在尝试使用angular fullstack构建一个实时投票应用程序。我的一切都在运转,除了当我收到选票时,我的百分比不会更新。我已经确定需要调用$scope.$apply以获得Angular来更新视图,但我不确定如何使用Angular fullstack提供的socket.service.js来实现这一点。我包括下面的角度全堆栈工厂。我不确定在我的控制器中调用$scope.$apply是否会有所不同。我试着将其作为socket.io函数的回调调用,但似乎没有什么不同。我对means和socket一般来说都是新手,所以我很感谢你的帮助 谢谢Angularjs Socket.io和$scope.$apply(),angularjs,socket.io,angularjs-scope,mean-stack,yeoman-generator-angular,Angularjs,Socket.io,Angularjs Scope,Mean Stack,Yeoman Generator Angular,我正在尝试使用angular fullstack构建一个实时投票应用程序。我的一切都在运转,除了当我收到选票时,我的百分比不会更新。我已经确定需要调用$scope.$apply以获得Angular来更新视图,但我不确定如何使用Angular fullstack提供的socket.service.js来实现这一点。我包括下面的角度全堆栈工厂。我不确定在我的控制器中调用$scope.$apply是否会有所不同。我试着将其作为socket.io函数的回调调用,但似乎没有什么不同。我对means和soc
angular.module('pollv1App')
.factory('socket', function(socketFactory) {
// socket.io now auto-configures its connection when we ommit a connection url
var ioSocket = io('', {
// Send auth token on connection, you will need to DI the Auth service above
// 'query': 'token=' + Auth.getToken()
path: '/socket.io-client'
});
var socket = socketFactory({
ioSocket: ioSocket
});
return {
socket: socket,
/**
* Register listeners to sync an array with updates on a model
*
* Takes the array we want to sync, the model name that socket updates are sent from,
* and an optional callback function after new items are updated.
*
* @param {String} modelName
* @param {Array} array
* @param {Function} cb
*/
syncUpdates: function (modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var oldItem = _.find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (oldItem) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
编辑
这是我的控制器:
'use strict';
angular.module('pollv1App')
.controller('VisualizeCtrl', function ($scope, $http, socket) {
$scope.votes = [];
$scope.totalVotes = 0;
$scope.resetVotes = function(){
$http.get('/api/keywords/reset');
$scope.votes = [];
console.log('reset: ' + $scope.votes);
};
$http.get('/api/keywords').success(function(keywords){
$scope.keywords = keywords;
socket.syncUpdates('keyword', $scope.keywords);
socket.syncUpdates('sms', $scope.votes, function(){
$scope.$apply();
});
});
$http.get('/api/sms').success(function(smss){
$scope.votes = smss;
});
});
最后,我从使用控制器和套接字获取总投票数改为使用自定义过滤器。这样,我就不用担心更新我的范围了。我从这篇文章中得到了这个想法: 你能告诉我你是怎么打电话/使用这项服务的吗?看看你在做什么cb@BlaShadow刚刚添加了我的控制器代码。谢谢你的关注!