AngularJS scope update from third-party aynchronous callback library

Hi, I am trying to use import.io to clear some football scores. I managed to get their JS to work with the API and deliver the data. The problem is that it must be in a closed space inside the controller, since I cannot execute ng-repeat on it.

Can someone tell me why, and also if someone has a good guide to the area, which is likely to be more helpful.

latestScores.controller('ScoresController', function ($scope) { $scope.pots = []; var io2 = new importio("XXX", "XXXXXX[API KEY]XXXXXXXX", "import.io"); io2.connect(function (connected) { if (!connected) { console.error("Unable to connect"); return; } var data; var callback = function (finished, message) { if (message.type == "DISCONNECT") { console.error("The query was cancelled as the client was disconnected"); } if (message.type == "MESSAGE") { if (message.data.hasOwnProperty("errorType")) { console.error("Got an error!", message.data); } else { data = message.data.results; } } if (finished) { pots = data; console.log(pots); /* This gives me an object */ } } io2.query({ "connectorGuids": [ "d5796d7e-186d-40a5-9603-95569ef6cbb9"], }, callback); }); console.log($scope.pots); /* This gives me nothing */ }); 
+6
source share
2 answers

angularjs data binding cannot know when you update the scope in a callback from a third-party library.

In your callback do the following:

 $scope.pots = dataReceived $scope.$apply(); 

If you want to skip calling $ scope.apply (), you need to use your own angular promise module (called $ q) and wrap your apis calls in the service.

In addition, if your API is based on websocket, you must subscribe to the $ scope.on ('$ destroy') event to disconnect from your api when the controller leaves.

+2
source

ng-repeat has its own scope. In your case, you assign data to a local variable, rather than assigning it to a region variable.

change this piece of code

 if (finished) { pots = data; console.log(pots); /* This gives me an object */ } 

to

 if (finished) { $scope.pots = data; console.log($scope.pots); /* This gives me an object */ } 
+1
source

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


All Articles