Asiri Liyana Arachchi Asiri Liyana Arachchi - 1 month ago 8
AngularJS Question

Broadcasting in angular does not give updated values in receiver

I'm broadcasting a set of coordinates and want that coordinates shown by a marker updated in every second.

var broadcastData = function (data) {
console.log("broadcasting data");
$rootScope.$broadcast('broadcast-started', data);
};


var waitingTime = 1000;

for(var i =0; i<data.length; i++){
var element = data[i];

var coordinates = new Object();
coordinates.latitude = element.LATITUDE;
coordinates.longitude = element.LONGITUDE;

setTimeout(function(){ broadcastData(coordinates);}, waitingTime);
waitingTime = waitingTime+1000;
}


Reciever

$scope.$on('broadcast-started', function (event, args) {
console.log(args);

console.log("received");
marker.setLatLng([args.latitude, args.longitude]);

});


Output:
enter image description here

Problem is even though coordinates are different in each iteration only the first set of coordinates are shown each time? I don't understand why that's happening

Answer

You need to use clouser function like this,

for(var i = 0; i < 10; i++) {
(function(i){  
     var element = data[i];

            var coordinates = new Object();
            coordinates.latitude = element.LATITUDE;
            coordinates.longitude = element.LONGITUDE;

            setTimeout(function(){ broadcastData(coordinates);}, waitingTime);
            waitingTime = waitingTime+1000;
})(i);}