动态添加内容到Angular承诺创建的元素中

Add Content To Dynamically, Angular Promise Created Elements

本文关键字:创建 元素 承诺 Angular 添加 动态      更新时间:2023-09-26

我有一个使用Angular Service获取数据的地图。数据被传递给一个函数,该函数通过它循环创建标记。每个循环调用一个函数,该函数应该为每个标记创建一个弹出窗口,但显示为空白。

当我将弹出内容记录到控制台时,它在几秒钟后出现,但我不知道如何将其传递给标记。我有一种感觉,这与闭包有关,我一直在研究这个问题。这是我的代码:

    //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;
} 

您需要从getPopupContent方法返回承诺,然后您可以在准备好时处理结果。实际上,您只是调用一个promise并返回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);
}