To create an object in a for loop and add a click function that calls another function while passing the index of the clicked object, you can use the following loop:
var markers = [];
for (x = 0; x < response.data.length; x++) {
var ret = {
onClicked: function (index) {
return function() { onMarkerClicked(index); };
}(x),
locationId: response.data[x].CASO_nid,
id: x,
latitude: response.data[x].Latitude,
longitude: response.data[x].Longitude,
title: x,
showWindow: false,
fit: true
};
markers.push(ret);
}
$scope.results = markers;
Upon inspecting the objects created in console, it is observed that all references to 'x' are correctly assigned except within the click function where it remains as just 'x'. This results in all objects referencing the last value of 'x'. To address this issue, you can modify the function logic as shown above to ensure each object holds its respective index value upon being clicked.
See in console:
0:
Objectfit: true
id: 0
idKey: 0
latitude: 42.0230636
locationId:10299
longitude: -87.9620276
onClicked: function () { onMarkerClicked(x); }
showWindow: false
title: 0