0

我正在嘗試使用angular-fullstack構建一個實時投票應用程序。除了當我收到投票時,我的所有工作都有效,我的百分比不會更新。我已經確定我需要調用$ scope。$ apply()以便讓Angular更新視圖,但我不確定如何使用angular-fullstack提供的socket.service.js來做到這一點。我在下面包括角度全堆棧工廠。我不確定是否在我的控制器中調用$ scope。$ apply()會有所作爲。我試圖將它稱爲我的socket.io函數的回調函數,但它似乎沒有什麼區別。我對MEAN和socket一般都很陌生,所以我很感激這個幫助。

謝謝!

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; 
    }); 
    }); 
+0

你能否也請說明你如何打電話/使用該服務? (看看你在做什麼) – BlaShadow 2014-10-06 19:56:25

+0

@BlaShadow剛剛添加了我的控制器代碼。感謝您的期待! – anguiac7 2014-10-06 20:13:15

回答

相關問題