Service with promise and $watchCollection not updating the values

丶灬走出姿态 提交于 2019-12-08 03:53:31

Thanks @Sunil for pointing that out. I originally thought, that $watch() and $watchCollection(), will pull automatically and check the service for new data based on specific interval provided by the $digest() cycle.

I released that my solution needs some kind of trigger, so that the new data to be pulled from the service when available. So I implemented private messaging channels using socket.io for triggering updates on message sent from the other party.

Here is the updated directive:

Updated directive.js:

angular.module('myApp').directive('messaging', ['$log', 'Messaging', 'messagingSocket', function($log, Messaging, messagingSocket){
  // Runs during compile
  return {
    scope: true,
    restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
    templateUrl: '/views/templates/messaging-dropdown.html',
    replace: true,
    link: function($scope, iElm, iAttrs, controller) {

      messagingSocket.emit('setUser', {id: $scope.user.id});

      $scope.allMessages = function(){

        Messaging.getAllMessages($scope.user.id).then(function(myData) {

          $scope.allMessages.messages = myData;

       }, function() {
           // request failed (same as your 'return false')
           $scope.allMessages = 'i got the error';
       });
      };

      $scope.allMessages();

      messagingSocket.forward('new message', $scope);

      $scope.$on('socket:new message', function (event, data) {

        $scope.allMessages();

      });

      $scope.$watchCollection('allMessages.messages', function(newVal, oldVal){
        if(newVal !== oldVal) {

            $scope.newMessages = 0;

            // Count the number of unread messages

            for (var i = $scope.allMessages.messages.length - 1; i >= 0; i--) {
               if($scope.allMessages.messages[i].read === false) {
                  $scope.newMessages++;
               }
            };
        }
    }, true);

    }
  };
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!