如何获取 $http.get 之外的变量值?

How to get variables value outside $http.get?

angularjs 的新手。我有一个简单的控制器,它使用 $http.get 读取 json 文件。在 get 中,我正在为变量 $scope.testTotal 分配一些值。但在退出 $http.get 时它们会恢复为默认值。令人困惑的是,当我将整个对象记录到控制台时,我可以看到这些值,但在记录特定值时它显示为零。可能是变量范围问题或执行顺序问题?

'use strict';
var app = angular.module("myApp", [ 'ngRoute']);

app.controller("SummaryController", ['$scope', '$http', function ($scope, $http) {

    $scope.testTotal = {
        executionStatus: { total: 0, passed: 0, failed: 0, duration: 0 }
    };

    $http.get('dummy.json').success(function (data) {
        $scope.data = data;
        angular.forEach($scope.data, function (i) {
            $scope.testTotal.executionStatus.passed += i.passed;
            $scope.testTotal.executionStatus.failed += i.failed;
        });
    });

    console.log($scope.testTotal); //I can see nested object with assigned values
    console.log($scope.testTotal.executionStatus.passed); //Vanished. Shows default value zero
}]);

dummy.json 有

[
    {"passed": 30, "failed": 12},
    {"passed": 10, "failed": 8}
]

编辑

我创建了 http://plnkr.co/edit/GlrrB0DkoAXCGpVsC2La。我的问题 objective 是:从嵌套的 json 文件(同步或异步)读取值,将其分配给 variable/object 并使用它制作图表。不幸的是,我无法访问我阅读的值。

$http.get 调用是异步的。在执行最后两行 console.log() 时,您已发送 AJAX 请求,但尚未收到响应。

收到后,将执行传递给 success() 的回调函数。只有这样,您才能知道新值并访问数据:

$http.get('dummy.json').success(function (data) {
    $scope.data = data;
    angular.forEach($scope.data, function (i) {
        $scope.testTotal.executionStatus.passed = 90;
        $scope.testTotal.executionStatus.failed = 25;
        $scope.testTotal.executionStatus.total = 115;
    });
    console.log($scope.testTotal); 
    console.log($scope.testTotal.executionStatus.passed);
});

请注意,forEach 循环没有多大意义:您在循环中为每个 $scope.testTotal.executionStatus 属性分配一个常量值。如果每次迭代都做同样的事情,为什么要使用循环?

$scope.testTotal.executionStatus.passed 是一个值,它会立即记录下来。由于 $http.get 是异步的,因此它是原始值。

$scope.testTotal 是包含其他对象的对象。要查看 passed 的值,您必须打开对象树。不是在打印 passed 的那一刻之前,那一刻它已经被赋予了新的价值。