javascript - 无法使用 AngularJS 更新变量

标签 javascript angularjs

我是 AngularJS 的新手,我正在尝试使用 .foreach 循环发送 http 请求。这是我的代码

app.controller('myCtrl', function($scope, $http) {
var rd;
$http.get(furl,config).then(function mySucces(response) {
rd = response.data;
var webcontent = "";
angular.forEach(rd, function(rd1){
    $http.get(furl1 + rd1.slug,config).then(function(res){          
    webcontent += res.data.title;
    console.log(webcontent);//console 1
    });
});
console.log(webcontent);//console 2
$scope.myWelcome = webcontent;
}, function myError(response) {$scope.myWelcome = response.statusText;});});

我预计控制台 2 将显示组合的“res.data.title”,但是,它只显示初始值。(在本例中为空)。控制台日志 1 显示正确 - 列出不断增加的“webcontent”变量。 不确定如何保持“webcontent”(控制台 2)更新值。任何回应将不胜感激!谢谢!

最佳答案

这不是一个 Angular 问题,这是一个异步 JavaScript 问题。你的代码在你的 promise 完成之前就完成了。您可以使用查询库等待所有 promise 得到解决,如下所示:

app.controller('myCtrl', function($scope, $http, $q) {
    var rd;
    $http.get(furl, config).then(function mySucces(response) {
        rd = response.data;
        var webcontent = "";
        var promises = [];

        angular.forEach(rd, function(rd1) {
            promises.push($http.get(furl1 + rd1.slug, config);
        });

        $q.all(promises).then(function (results) {
            angular.forEach(results, function (result) {
                webcontent += result.data.title;
            }

            $scope.myWelcome = webcontent;
        });
    }, function myError(response) {
        $scope.myWelcome = response.statusText;
    });
});

关于javascript - 无法使用 AngularJS 更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36652792/

相关文章:

javascript - 如何制作动画标题以显示在手机和平​​板电脑上?

javascript - 让我的用户使用 Google 登录的首选 JavaScript 方法实际上是什么?

javascript - 使用悬停和 Angular 更改 div 的颜色时出错

javascript - 单击不应发送表单的按钮时如何在 Angular 中关闭表单验证

c# - Webdriver 无法单击带有证书错误页面的弹出窗口

JavaScript - 删除 </html> 标签后的所有内容

javascript - 是否有任何 cookie 可以指示用户是否已登录 Google Chrome 浏览器?

angularjs - 在 angularJS 中使用 $http.post 时出现 undefined index 错误

javascript - 在 Ionic 应用程序中发送电子邮件会导致以下错误 : TypeError: $cordovaEmailComposer. isAvailable is not a function

angularjs - 如果 ng-repeat 逻辑包含在 ng-if 中,它是否会触发