Sonic Soul
Sonic Soul

Reputation: 24899

Frequent updates to Angular controller not reflected in view

Working on an interesting issue with Angular and frequent updates from SignalR.

on the server, I have a singleton instance of a manager which is currently set to send updates every 500ms

    public void StartTest() {
        var i = 0;
        while (i < 1000) {
            if (_cancelRequested) {
                _cancelRequested = false;
                return;
            }
            _context.Clients.All.sent(i++);
            Thread.Sleep(500);            

in my view i'm using "controller as vm" syntax:

{{vm.status}}

finally in my controller (on signalR initialization):

    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
    var vm = this;
    vm.status = '';
    ...
    function activateSignal() {
        var hub = $.connection.mailerHub;

        hub.client.sent = function (counter) {
            log(' singal_R ## event: sent ' + counter);  // <-- this works on every update
            vm.status = counter;  // this works only on last update, or if stop is pressed it writes the most recent update. 
        };

that code does 2 things: writes to log (this sends a toastr update to the browser), and sets the status variable on the controller.

the log comments are reflected in the browser as expected, every half second i get the nice toastr notification with event number, however setting the variable doesn't have any effect, until i request stop, or it reaches 999.

when i press stop, vm.status gets written out with last sequence number, or when the entire thing stops, it writes out 999.

so it appears to be some issue with frequency of setting properties on vm? would i need something like $scope.$watch to make this work?

Upvotes: 1

Views: 467

Answers (1)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78559

Well, it is not clear enough for me exactly what you are trying to achieve, but it looks like you are updating your model outside the control of angular. So, you need to notify angular of what you are doing.

Most likely, something like this should solve the problem:

hub.client.sent = function (counter) {
   $scope.apply(function(){
      log(' singal_R ## event: sent ' + counter);
      vm.status = counter;
   });
};

Upvotes: 4

Related Questions