Dynamically update a model from a web socket

Update (idea / high-level concept)

To summarize, I would like the values ​​to be dynamically updated in the controller, which is bound to the Socket Socket service, whose value is changing. Below is my attempt to solve the problem and the barrier I encountered.


I would like to update the view model in the controller, every time the socket outputs information to the service. To imitate clicking messages, I just call a timeout every second, which, in turn, increases the value of working capacity in the service that I checked, it works in the console.

Although the health value inside the controller is never updated, and I lose what I am doing wrong. The following are snippets of reference code.

This is the controller

(function () {
    'use strict';
    angular
        .module('xxx')
        .controller('DashboardController', ['$scope','$timeout', "$uibModal", "dashboardService", "syncService", DashboardController]);

    function DashboardController($scope, $timeout, $uibModal, dashboardService, syncService) {
        var vm = this;

        // VERSIONS
        vm.versions = {};

        // HEALTH
        vm.health= syncService.health;

        // JUMP-START
        activate();

        //////////////

        function activate(){
           getVersions();
        }

        function getVersions(){
            dashboardService.getVersions()
                         .then(function(data) {
                            vm.versions = data;
                            return vm.versions;
                         });
        }

    }
})();

This is a service.

    (function () {
        'use strict';
        angular
            .module('xxx')
            .service('syncService',['$timeout', syncService]);

        function syncService($timeout) {
            //Init WebSocket
            var self = this;
            self.health= 0;
            updatedStatus();
            ///////////

            ....

        function updatedStatus(){
            $timeout(updatedStatus, 1000);
            self.health += 1;
            $timeout(angular.noop);   
        };
    }
})(); 

Update


, , $scope. , , question

+4
1

AFAIK, . , , :

  function DashboardController($scope, $timeout, $uibModal, dashboardService, syncService) {
    var vm = this;

    // VERSIONS
    vm.versions = {};

    // HEALTH
     vm.syncService = syncService;

     $scope.$watch('vm.syncService.health', function(newHealth, oldHealth){
        vm.health = newHealth;
     })

    // JUMP-START
    activate();

    //////////////

    function activate(){
       getVersions();
    }

    function getVersions(){
        dashboardService.getVersions()
                     .then(function(data) {
                        vm.versions = data;
                        return vm.versions;
                     });
    }

}

, $broadcast, .

+1

Source: https://habr.com/ru/post/1648690/


All Articles