简体   繁体   中英

Angular.js - $scope.variable doesn't auto update

I have the following code

// Generated by CoffeeScript 1.6.3
(function() {
  "use strict";
  var chatModule;

  chatModule = angular.module('chatModule', ['diplomovaPraceFrontendApp']);

  chatModule.service('chatModuleService', function(UserService, socket) {
    var obj,
      _this = this;
    obj = {};
    obj.chats = [];
    obj.initiate = function(from) {
      if (!_.has(obj.chats, from)) {
        return obj.chats[from] = {
          messages: []
        };
      }
    };
    obj.logIncoming = function(data) {
      return obj.chats[data.from].messages.push({
        text: data.message,
        type: 'in'
      });
    };
    obj.send = function(chat) {
      return socket.emit('private-message', {
        to: chat.profile_hash,
        from: UserService.profile_hash,
        message: chat.message
      });
    };
    socket.on('private-message', function(data) {
      return obj.logIncoming(data);
    });
    return obj;
  });

  chatModule.directive('chat', function() {
    return {
      restrict: 'E',
      templateUrl: 'scripts/modules/ChatModule/chatModule.html'
    };
  });

  chatModule.controller('ChatCtrl', function($scope, chatModuleService) {
    $scope.send = function(chat) {
      return chatModuleService.send(chat);
    };
    return $scope.chats = chatModuleService.chats;
  });

}).call(this);

If I am not mistaken, when changing the service's value, being assigned to the $scope , it should automatically update the $scope 's variable and therefore update corresponding the HTML. But this doesn't seem to be happening.

I solved it myself, the problem was:

obj.chats = [];

is supposed to be:

obj.chats = {};

The best is console didn't give me any errors or a clue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM