Socket.io和$ scope。$ apply()

时间:2014-10-06 19:12:32

标签: angularjs socket.io angularjs-scope mean-stack yeoman-generator-angular

我正在尝试使用angular-fullstack构建一个实时投票应用程序。我有一切工作,除非我收到投票,我的百分比不更新。我已经确定我需要调用$ scope。$ apply()以使Angular更新视图,但我不知道如何使用angular-fullstack提供的socket.service.js来做到这一点。我在下面包括angular-fullstack工厂。我不确定是否在我的控制器中调用$ 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;
    }); 
  });

1 个答案:

答案 0 :(得分:0)

最后,我改变了使用控制器和Socket以获得使用自定义过滤器的总投票数。这样,我就不用担心更新我的范围了。我从这篇文章中得到了这个想法:Increment A Variable In AngularJS Template