Angularfire forEach键返回undefined

时间:2014-03-12 09:44:44

标签: angularjs firebase angularfire

我有一些数据

{
    "projects" : [
        {
            "projectName" : "Test Project 1",
            "dueDate" : "20/05/2014",
            "owner" : "Test owners 1",
            "categories" : [
                "JavaScript",
                "HTML",
                "CSS"
            ],
            "open" : true,
            "tasks" : [
                {
                    "taskName" : "Test task 1",
                    "targetDate" : "02/04/2014",
                    "categories" : [
                        "JavaScript",
                        "HTML",
                        "CSS"
                    ],
                    "open" : true
                },
                {
                    "taskName" : "Test task 2",
                    "targetDate" : "10/04/2014",
                    "categories" : [
                        "JavaScript",
                        "HTML"
                    ],
                    "open" : true
                }
            ]
        },
        {
            "projectName" : "Test Project 2",
            "dueDate" : "12/07/2014",
            "owner" : "Test owners 2",
            "categories" : [
                "JavaScript",
                "HTML",
                "CSS"
            ],
            "open" : true,
            "tasks" : [
                {
                    "taskName" : "Test task 1",
                    "targetDate" : "13/05/2014",
                    "categories" : [
                        "HTML",
                        "CSS"
                    ],
                    "open" : true
                },
                {
                    "taskName" : "Test task 2",
                    "targetDate" : "03/06/2014",
                    "categories" : [
                        "JavaScript"
                    ],
                    "open" : true
                }
            ]
        }
    ]
}

然后我有一个简单的控制器试图输出每个数组索引中包含的对象

TM.factories.getData = function(){
    var getProjects = new Firebase("https://<my-firebase>.firebaseio.com/projects");
    return getProjects;
};

TM.controllers = {};

TM.controllers.overviewCtrl = function($scope,$firebase){
    var taskArr = [];
    $scope.projectList =  $firebase(TM.factories.getData());
    $scope.projectList.$on("loaded", function() {
        $scope.projectList.$getIndex().forEach(function(key,i) {
            console.log($scope.projectList[key]);
        });
    });
};

不要担心它是如何布局的我尝试以不同的方式编写它并且它是非常早期的开发工作。

问题是为什么我在使用&#34; key&#34;时会得到未定义或者&#34;我&#34;?如果我只是控制日志&#34;键&#34;或&#34;我&#34;我得到0,1。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

TM.controllers.overviewCtrl = function($scope,$firebase){
    var taskArr = [];
    $scope.projectList =  $firebase(TM.factories.getData());
    $scope.projectList.$on("loaded", function(projectList) {
        projectList.$getIndex().forEach(function(value,key) {
            console.log(projectList[key]);
        });
    });
};