在角度控制器中访问HTTP GET JSON属性

mod*_*ler 8 javascript json angularjs

我在angular.js和$ http.get方法中使用工厂来获取和处理JSON数据.JSON数据似乎已成功解析为工厂,但我有此JSON数据的访问属性问题.

这是我的js代码:

var app = angular.module("app", []);      

app.factory('mainInfo', function($http) { 

    var obj = {content:null};
    //the php will return json data below
    $http.get('http://localhost/test.php').success(function(response){ 
        obj.content = response.records;

    });    

    return obj;    
});


app.controller('Ctrl', function($scope, mainInfo){
    $scope.foo = mainInfo.content;
}) ;
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试中访问FOO Ctrl控制器,该网页将显示任何数据:
<div ng-controller="Ctrl">Controller: {{foo}}</div>
但是,如果我改变$scope.foo = mainInfoCtrl,那么该网页将正确显示JSON数据.

我可以知道mainInfo.contentCtrl控制器中访问属性的正确方法是什么?

我需要访问JSON属性的原因是因为我需要预处理数据.我打算在图表中使用这些数据,如下面的控制器.目前这个控制器也不工作,因为我在Ctrl控制器中访问JSON属性时遇到同样的问题.

app.controller("LineCtrl", function ($scope, mainInfo) {
    var timePoints = [];
    var percentagePoints = [];
    var i = 0;
    for( i = 0; i < mainInfo.content.length; i ++) {
        timePoints.push(mainInfo.content[i].Time);
        percentagePoints.push(mainInfo.content[i].Percentage);
    }

    $scope.labels = timePoints;

    $scope.data = percentagePoints;

    $scope.onClick = function (points, evt) {
        console.log(points, evt);
    };
});
Run Code Online (Sandbox Code Playgroud)

json数据:

{
"records": [
    {
        "Id": "1",
        "Time": "2015-07-25 08:00:00",
        "Percentage": "60"
    },
    {
        "Id": "2",
        "Time": "2015-07-25 09:00:00",
        "Percentage": "70"
    },
    {
        "Id": "3",
        "Time": "2015-07-25 10:00:00",
        "Percentage": "80"
    }
    ]
}
Run Code Online (Sandbox Code Playgroud)

关于工厂 - 控制器通信,我只是从另一篇文章中引用解决方案:参考

Wil*_*m B 7

$ http.get返回一个承诺 - 你的问题是,你是立即返回"目标文件",你的控制器试图访问$ http.get承诺之前的数据得到解决.

像这样使用$ http(不需要使用$ q.defer(),如另一条评论所示):

var app = angular.module("app", []);      

app.factory('mainInfo', function($http) { 
    var getRecordsPromise = $http.get('http://localhost/test.php').then(function(response){ 
        //whatever is returned here will be accessible in the .then that is chained
        return response.data.records;
    });    

    return {
        getRecords: getRecordsPromise
    };    
});


app.controller('Ctrl', function($scope, mainInfo){
    mainInfo.getRecords.then(function (records) {
        $scope.foo = records;
    });
}) ;
Run Code Online (Sandbox Code Playgroud)