[英]AngularJS - Displaying data from API
我是AngularJS的新手,在顯示來自api調用的數據時遇到問題。
我想顯示標題,但有時會卡住。 有人可以幫我遍歷嗎?
這是我的index.html
controller.js
var app = angular.module('myApp', []);
app.controller('appController', function($scope) {
//console.log("test");
var url = "https://api.nytimes.com/svc/topstories/v2/home.json";
url += '?' + $.param({
'api-key': "853fc084776f46e29732e71b3f1269ae"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
$scope.results = result;
}).fail(function(err) {
throw err;
});
});
這是我的json
您提供的JSON是對象數組,而對象數組又包含帶有標題的對象數組。
因此,您將需要一個如下所示的嵌套數組,以顯示JSON響應中的所有標題。
<div ng-repeat="result in results">
<div ng-repeat="child in result.results">
{{child.title}}
</div>
</div>
您遇到了兩個問題,第一個是在angular有自己的http服務(已使用jquery ajax)時,在angular中使用了jquery,因此結果變量將不會在將要打印的控制台中的html上為您提供,但您無法訪問html,所以我們必須像下面這樣寫。
$scope.$apply(function(){
$scope.results = result.results;
});
現在循環看下面的代碼
<div ng-app="myApp" ng-controller="appController">
<ul>
<li ng-repeat="x in results">
{{x.title}}
<li>
</ul>
</div>
工作碼筆鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.