ng-repeat Angular and JSON array

自闭症网瘾萝莉.ら 提交于 2019-12-25 09:46:48

问题


I'm new to Angular and I'm trying to set up a simple display. I've looked through the documentation on ng-repeat and have done some of the tutorials with success every time. However, when I went to do a mock of my own I can't get anything to show from the JSON file. Even using the often found Angular "todo.json" example found everywhere I still am unable to figure this one out. I'm not sure if it has to do something with JSON or possibly nesting the ng-repeat. Can anyone guide me to seeing the light?! hehe. Thanks in advance.

So, here's the Plunker link. http://plnkr.co/edit/8rNgPHUHEe88Gpw6aM1D

HTML:

    <!doctype html>
<html ng-app="App" >
<head>
  <meta charset="utf-8">
  <title>Todos $http</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="Calendar">
  <ul>
    <li ng-repeat="items in events">
      {{items.events}}
    </li>
  </ul>
</body>
</html>

JS:

var App = angular.module('App', []);

App.controller('Calendar', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.events = res.data;                
        });
});

JSON:

[
    {
        "events": [
            {
                "EventTitle": {
                    "href": "http://example.com/event1",
                    "text": "HEADLINE TEXT FOR EVENT 1"
                },
                "HeadlineImage": {
                    "href": "http://example.com/event1",
                    "src": "http://example.com/Image.jpg",
                    "text": "CAPTION TEXT FOR IMAGE "
                },
                "Eventdescription": "Lorem Loreem Loreeem Ipsum Ipsuum Ipsuuum ..."
            }
        ]
    }
]

回答1:


If you must keep this structure, then you need to do something like this

<ul>
  <li ng-repeat="items in events">
    <a href="{{items.EventTitle.href}}">{{items.EventTitle.text}}</></a>
  </li>
</ul>

controller:

App.controller('Calendar', function($scope, $http) {
  $http.get('todos.json')
       .then(function(res){
          $scope.events = res.data[0].events;             
        });
});

Here's a forked plunker

Edit: The revised plunker, using the above changes. The scope var should be res.data.events

Updating after a new json structure provided: Here's a working example with actual json data




回答2:


Your data structure is pretty weird. Check an updated working plunker: http://plnkr.co/edit/SXHjqxjZ2bgJSs327jz4?p=preview

You can use <pre>{{ events | json }}</pre> in your view to easily inspect/debug objects.



来源:https://stackoverflow.com/questions/27115100/ng-repeat-angular-and-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!