javascript - 变量在for循环中被覆盖

标签 javascript angularjs for-loop

对于每个事件,其地点都不同。但是,当它显示在 UI 上时,所有位置都已被最后一次 API 调用覆盖。我怎样才能阻止这种情况发生?

$scope.eventLoc = '';
    API.get({entity: 'organisation', entity_id: oid, property: 'campaign', property_id:cid, property2:'events'}, function(resp) {
        $scope.orgEvents = resp.data;
        for (i in resp.data) {
            ceid = resp.data[i].CampaignEventID;
            lid = resp.data[i].LocationID;
            API.get({entity: 'location', entity_id: lid}, function(respLocation){
                $scope.eventLoc = respLocation.data;
            })
        }
    });

<li ng-repeat="event in orgEvents track by $index">
    <h2>{{event.Name}}</h2>
    {{eventLoc.Address1}}
</li>

最佳答案

只需将代码更改为如下所示:

//$scope.eventLoc = ''; //this can be removed
    API.get({entity: 'organisation', entity_id: oid, property: 'campaign', property_id:cid, property2:'events'}, function(resp) {
        $scope.orgEvents = resp.data;
        angular.forEach($scope.orgEvents, function(orgEvent) {
            //ceid = orgEvent.CampaignEventID; //this is not being used?
            lid = orgEvent.LocationID;
            API.get({entity: 'location', entity_id: lid}, function(respLocation){
                orgEvent.eventLoc = respLocation.data;
            });
        });
    });

<li ng-repeat="event in orgEvents track by $index">
    <h2>{{event.Name}}</h2>
    {{event.eventLoc.Address1}}
</li>

关于javascript - 变量在for循环中被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119045/

相关文章:

javascript - 当在其中调用函数时,事件监听器处理程序上下文会发生什么?

javascript - html 标签的分割值

javascript - Angular : Pass arguments from Directive to event/expression

javascript - AngularJS:$http.get方法下载pdf文件

javascript - 使用for循环使用整数序列填充数组,而不会导致Chrome崩溃

python-3.x - 如何匹配两个 DataFrame 中的特定值并在 Python Pandas 中添加额外的列?

javascript - 无论缩放和滚动如何,都将 div 定位在特定的固定位置

javascript - 不使用服务器保存和加载 mxGraph 文件

angularjs - 在 <tr> 元素中设置 ng-href

python - PyQt4 GUI 中的标签不会随着 FOR 循环的每个循环而更新