指定正确的ng-repeat标签时出现问题

时间:2014-06-02 16:56:26

标签: javascript angularjs angularjs-ng-repeat

我是AngularJS的新手。

我正在尝试使用ng-repeat在页面上显示博客条目。

如何正确指定ng-repeat标签的正确属性,我感到有些困惑。

我的JSON数据源。这是使用X2JS从XML文件转换的:

{
    "blog": {
        "article": [
            {
                "id": "1",
                "author": "eat-sleep-code",
                "title": {
                    "__cdata": "The first article."
                },
                "content": {
                    "__cdata": "\n        This is my first article in my test site.\n      "
                },
                "createdate": "2014-05-09"
            },
            {
                "id": "2",
                "author": "eat-sleep-code",
                "title": {
                    "__cdata": "The second article."
                },
                "content": {
                    "__cdata": "\n        This is my second article in my test site.  This article's create date is actually earlier.\n      "
                },
                "createdate": "2014-05-08"
            }
        ]
    }
}

我的部分观点:

<article ng-repeat="article in data.blog">
    <h2>{{title}}</h2>
    {{content}}
    {{id}}  
</article>

我的app.js:

//Define an angular module for our app
var app = angular.module('eatsleepcode', ['ngRoute']); 

//Define Routing
app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {    
        $routeProvider.      
            /* Root */
            when('/', {templateUrl: 'views/home.html', controller: 'DefaultController'}).
            when('/blog', {templateUrl: 'views/blog.html', controller: 'BlogController'}).  
            otherwise({
                redirectTo: '/404'
            });
            $locationProvider.html5Mode(false);
            $locationProvider.hashPrefix("!");
}]);  




/* Controllers */
app.controller('DefaultController', function($scope) {});

app.controller('BlogController', function($scope, $routeParams, $http) {
    $http({method: 'GET', url: '//eat-sleep-code.com/data/blog.xml'}).
        success(function(data, status) {
            var x2js = new X2JS();
            var jsonString = JSON.stringify(x2js.xml_str2json(data));
            $scope.data = jsonString;
            $scope.status = status;
            console.log('DATA: ' + jsonString);
            console.log('STATUS: ' + status);
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
            console.log('STATUS: ' + status);
        });
});

当我查看Google Chrome中的元素时,我看到:&lt;! - ngRepeat:data.blog中的文章 - &gt;但实际上并没有重复。

1 个答案:

答案 0 :(得分:1)

您需要在数组上使用ng-repeat并且data.blog是一个对象而不是数组。

而不是

<article ng-repeat="article in data.blog">

尝试使用:

<article ng-repeat="article in data.blog.article">
    <h2>{{article.title.__cdata}}</h2>

article是您想要枚举的属性。

修改另请注意,您希望显示的元素title有一个子属性,其中包含您要显示的名为__cdata的文本