阅读JSON并使用Angular JS绘制它

时间:2015-07-23 08:12:58

标签: javascript json angularjs

我有这个JSON:

[
    {
        "_id": "55afa124168fa1652ce4df21",
        "title": "My New Book",
        "genre": "Fiction",
        "author": "Jon Mills",
        "__v": 0,
        "read": false,
        "links": {
            "self": "/api/books/55afa124168fa1652ce4df21"
        }
    }
]

如何显示作者和标题列表?

这是我到目前为止所尝试的:

<div ng-app="myApp" ng-controller="customersCtrl"> 
  <ul>
    <li ng-repeat="x in _id">
      {{ x.title + ', ' + x.author }}
   </li>
  </ul>
</div>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("api/books")

.success(function (response) {
alert("Response:" + response.title + " - " + response.author)
     }
   }
 alert(vals);
}
});
});

2 个答案:

答案 0 :(得分:2)

示例:

Controler Js

angular.module('myApp', []);

function TestCtrl($scope,$http) {

  $http.get("api/books").success(function (response) {
     $scope.dataList = response;
  });

}

Html文件

<div ng-controller="TestCtrl">
<ul>
    <li ng-repeat="data in dataList">
      {{ data.title}} , {{data.author }}
   </li>
  </ul>
</div>

答案 1 :(得分:1)

您无法通过 _id 访问标题作者,因为无法使用其他媒体资源访问该媒体资源 例如:

var obj={
x:1,
y:2
}

我不能写x.y它将是一个无效的表达式

如果要迭代,可以使用数据执行此操作

HTML

<div ng-app="myApp" ng-controller="customersCtrl"> 

 <ul>
   <li ng-repeat="x in data">
    {{ x.title}} ,  {{ x.author }}
   </li>
</ul>

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.data = [{
  "_id": "55afa124168fa1652ce4df21",
  "title": "My New Book",
  "genre": "Fiction",
  "author": "Jon Mills",
  "__v": 0,
  "read": false,
  "links": {
    "self": "/api/books/55afa124168fa1652ce4df21"
  }
}, {
  "_id": "55afa124168fa1652ce4df22",
  "title": "My New Book2",
  "genre": "Fiction2",
  "author": "Jon Mills2",
  "__v": 1,
  "read": false,
  "links": {
    "self": "/api/books/55afa124168fa1652ce4df22"
  }
}];

});