使用AngularJS将值从JSON http.get传递到scope.value

时间:2014-11-10 07:35:39

标签: angularjs angularjs-scope

我目前正在编写一个代码,将json中的文件显示为图表JS。

var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {

    var viewAll = this;
    viewAll.gauge = [];
    $http.get('dom/json/cpuUsage.json').success(function(data){
        viewAll.gauge = data;
    });

    $scope.value = viewAll.gauge[0].value;

但是,我很难从变量数组viewAll.gauge中取出值。我遇到了错误:

Error: viewAll.gauge[0] is undefined
@http://localhost:8080/js/directives/cpusagegauge.js:11:2
e@http://localhost:8080/js/angular.min.js:35:343
h/<.instantiate@http://localhost:8080/js/angular.min.js:35:474
ce/this.$get</<@http://localhost:8080/js/angular.min.js:68:140
x/<@http://localhost:8080/js/angular.min.js:54:226
q@http://localhost:8080/js/angular.min.js:7:384
x@http://localhost:8080/js/angular.min.js:54:89
g@http://localhost:8080/js/angular.min.js:48:28
g@http://localhost:8080/js/angular.min.js:48:1
g@http://localhost:8080/js/angular.min.js:48:1
x@http://localhost:8080/js/angular.min.js:55:10
g@http://localhost:8080/js/angular.min.js:48:28
x@http://localhost:8080/js/angular.min.js:55:10
z/<@http://localhost:8080/js/angular.min.js:61:261
l/k.success/<@http://localhost:8080/js/angular.min.js:73:32
Re/e/m.promise.then/L@http://localhost:8080/js/angular.min.js:99:147
Re/e/m.promise.then/L@http://localhost:8080/js/angular.min.js:99:147
Re/f/<.then/<@http://localhost:8080/js/angular.min.js:100:321
me/this.$get</g.prototype.$eval@http://localhost:8080/js/angular.min.js:111:1
me/this.$get</g.prototype.$digest@http://localhost:8080/js/angular.min.js:108:458
me/this.$get</g.prototype.$apply@http://localhost:8080/js/angular.min.js:112:323
g@http://localhost:8080/js/angular.min.js:73:285
x@http://localhost:8080/js/angular.min.js:77:322
Ne/</y.onreadystatechange@http://localhost:8080/js/angular.min.js:78:358

http://localhost:8080/js/angular.min.js
Line 93

BTW,我的JSON文件非常小。

[{
"value": "80"
}]

1 个答案:

答案 0 :(得分:0)

问题是$http.get()的回调是异步调用的。在您的情况下,viewAll.gauge = data;$scope.value = viewAll.gauge[0].value;

之后被称为

以下内容应该有效:

var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
    function($scope, $http) {

    var viewAll = this;
    viewAll.gauge = [];
    $http.get('dom/json/cpuUsage.json').success(function(data){
        $scope.value = data.gauge[0].value;
    });
})

此外,如果要在异步回调中更新范围变量,则必须将其包装在$scope.$apply(function() { //your code goes here });中。以下是完整的示例:

var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
    function($scope, $http) {

    var viewAll = this;
    viewAll.gauge = [];
    $http.get('dom/json/cpuUsage.json').success(function(data){
        $scope.apply(function() {
            $scope.value = data.gauge[0].value;
        });
    });
})