emerfan emerfan - 3 months ago 8
AngularJS Question

Add Content To Dynamically, Angular Promise Created Elements

I have a map which uses an Angular Service to get data. The data is passed to a function which loops through it creating markers. Each loop calls a function which should create a popup for each marker, but shows up blank.

When I log the popup content to the console, it shows up after a few seconds, but I can't figure out how to pass it to the marker. I have a feeling it's something to do with closures, which I have been investigating. This is my code:

//Create the Markers Function
var createMapMarkers = function (data) {
angular.forEach(data, function (value, key) {

//Calling the get popup content function here
var content = getPopupContent(value.AreaName, value.ImageUrl);

var marker = L.marker([value.Lat, value.Long])
.bindPopup(content)
.addTo($scope.map);
});
}

function getPopupContent(areaName, imageUrl) {
var response;
$http.get('/Home/GetPopupContent?areaName=' + areaName + '&imageUrl=' + imageUrl)
.then(function (response) {
//This logs the correct content
console.log(response);
});
//But it does not return here
return response;
}

Lee Lee
Answer

You need to return the promise from your getPopupContent method, and then you can work on the result when it is ready. As it is, you are just calling a promise and returning undefined.

var createMapMarkers = function (data) {
    angular.forEach(data, function (value, key) {

        //Calling the get popup content function here
        getPopupContent(value.AreaName, value.ImageUrl).then(function(content) {
            var marker = L.marker([value.Lat, value.Long])
                         .bindPopup(content)
                         .addTo($scope.map);
        });
    });
}

function getPopupContent(areaName, imageUrl) {
    return $http.get('/Home/GetPopupContent?areaName=' + areaName + '&imageUrl=' + imageUrl);
}
Comments