H
H
HoHsi2015-10-12 16:43:37
Angular
HoHsi, 2015-10-12 16:43:37

Why doesn't Angular.js update View on Socket.io event?

Good day!
Why doesn't Angular update the DOM on a Socket.io event? Although if you output console.log data, then the date is not undefined.
CoffeeScript:

do (window, angular, io)->
    adminApp = angular.module('adminApp', [])
    socket = io.connect '/', {
        path: '/admin/socket.io'
    }

    adminApp.controller 'ProgressCtrl', [
        '$scope'
        ($scope) ->
            $scope.stats = {
                cpu:
                    percent: 10
                memory:
                    percent: 70
            }

            socket.on 'server:stats', (data) ->
                $scope.stats.percent = data.os.percent * 100
    ]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Shchetinin, 2015-10-12
@draedful

Because the socket works asynchronously and angular doesn't know about the change of the variable. In order for angular to check this variable, you need to force it to do so, for this you can either call the $scope.$apply() or $scope.$digest() function or wrap the code that changes the data in a construct

$timeout(function(){
// тут код
})

But there is one problem with using $scope.$apply() and $scope.$digest() functions, if digest is already running, angular crashes, so I advise you to use $timeout

R
Radiks Alijevs, 2015-10-12
@dedalik

Good day!
You need to put scope.$watch() on property changes in scope. See the documentation for an example https://docs.angularjs.org/api/ng/type/$rootScope.Scope , section $watch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question