15

This will be one of those stupid questions that is very obvious to the experts.

I have a websocket pushing data to a service where I'm trying to store the data and have it pushed to a template via my controller.

The data is coming in and updating the variable but the UI only updates is I perform a action on that data:

services.factory('Summary', ['$q','$rootScope','$http', '$location', function ($q, $rootScope,$http, $location) {

var Service = {};
Service.dataObj = {};
Service.dataObj.d = {"gello":"goodbye"};
....
function listener(data) {
   messageObj = data;
    Service.dataObj.d = data;
  console.log("Received data from websocket: ", messageObj);

}
})]);


controllers.controller('UserCtrl', ['$scope', 'Summary',
function ($scope, Summary) {

    $scope.click = function(){
        alert(JSON.stringify($scope.summaryinfo));
    }
    $scope.summaryinfo = [Summary.dataObj];
    $scope.summarygridOptions = {
        data: 'summaryinfo'
    };
    console.log("hello");
}]);

The data gets pumped in and as far as I was aware because its being stored in Service.dataObj.d if I point my HTML template at Service.dataObj that object is being updated and not replaced so the pointer should remain and the object be watched.

But it doesn't change unless I run the click() method, in which case the UI is affected even though Im just triggering an alert.

What am I missing?

2
  • try use scope.$apply to apply the change. Commented Jan 6, 2014 at 16:31
  • spend 4 hours last night trying to figure out what the hell is going on... woke up this morning saw your question and fixed it in 3 mins! Thanks bugg_tb! Commented Feb 13, 2016 at 8:33

1 Answer 1

21

You probably need to use $apply():

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

function listener(data) {
   $scope.$apply(function() {
       Service.dataObj.d = data;
   });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks guys, knew it would be obvious. I have similar calls in a different project but clearly the initialisation must be different as I don't rely on $apply. As ever something new to learn :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.