使用AngularJS循环遍历JSON文件时出现“格式不正确”的firefox错误

时间:2013-09-17 12:52:18

标签: javascript json firefox angularjs

JSON文件结构如下:

{
    "meta": {
        "limit": 20, 
        "next": null, 
        "offset": 0, 
        "previous": null, 
        "total_count": 2
    }, 
    "objects": [
        {
            "description": "Lorem ipsum dolor sit amet ....Lorem ipsum dolor sit amet ....Lorem ipsum dolor sit amet ....", 
            "end": "2013-09-09T15:37:24", 
            "id": 1, 
            "name": "Lorem ipsum dolor sit amet ....Lorem ipsum dolor sit amet", 
            "resource_uri": "/api/task/1/", 
            "start": "2013-09-09T15:37:23"
        },
        {
            "description": "Here goes description :) Here goes description :) Here goes description :) ", 
            "end": "2013-09-11T15:58:01", 
            "id": 2, 
            "name": "Some other task", 
            "resource_uri": "/api/task/2/", 
            "start": "2013-09-11T15:58:00"
        }
    ]
}

我试图像这样循环:

<!DOCTYPE html>
<html lang="en" ng-app id="ng-app">
    <head>
        <title>Angular studies</title>
        <meta charset="UTF-8" />
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <script>
        function PostsCtrlAjax($scope, $http) {
        $http({method: 'POST', url: 'posts.json'}).success(function(data) {
                $scope.tasks = data;
            });
        }
        </script>
    </head>
    <body>
        <div id="ng-app" ng-app ng-controller="PostsCtrlAjax"> 

        <div ng-repeat="task in tasks">
           <a href='{{task.id}}'>{{task.name}}</a>
        </div>

        </div>
    </body>
</html>

为此,我在Firefox中收到“格式不正确”的错误。你能告诉我一个修补这个的方法吗?

1 个答案:

答案 0 :(得分:2)

这确实是有效的JSON。问题是您尝试迭代tasks,但实际上想要迭代tasks.objects

for (var i=0;i<tasks.objects.length;i++) {
    console.log(tasks.objects[i].id);
    console.log(tasks.objects[i].name);
}

输出

1 
Lorem ipsum dolor sit amet ....Lorem ipsum dolor sit amet 
2 
Some other task 

我不熟悉角度语法,但我想这是你想要/真正尝试做的事情:

<div ng-repeat="task in tasks.objects">