2014-10-08 64 views
0

我只是好奇,在如何訪問此JSON調用中的任何字段,因爲它有多個對象,是非常困惑,因爲這是我第一次處理這個。這裏是鏈接到JSON: http://api.wunderground.com/api/5ad0204df4bdbeff/forecast/q/Australia/Sydney.json?callback=JSON_CALLBACKJSON AngularJS多個對象

我的代碼使用AngularJS調用JSON,然後將其存儲。綁定值然後通過循環訪問它。

<!DOCTYPE html> 
<html ng-app="plunker"> 

    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 

    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script> 
    <script > 

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

app.controller('MainCtrl', function($scope, $http) { 
    $http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/forecast/q/Australia/Sydney.json?callback=JSON_CALLBACK').success(function(data){ 
    console.log(data); 
    $scope.weatherData=data; 
    }) 
}); 
    </script> 
    </head> 

    <body ng-controller="MainCtrl"> 
    <ul> 
     <li ng-repeat="weather in weatherData"> 
      {{weather.celsius}} 
     </li> 
    </ul> 
    </body> 

</html> 

本質上我想訪問「simpleforecast」對象,然後訪問溫度區域。我將如何去做這件事?

+0

你在console.log(data)中收到了什麼; ? – Artemis 2014-10-08 09:53:18

+0

對象{response:Object,forecast:Object}但是你可以進一步擴展它 – Indrick 2014-10-08 09:56:35

+0

,這樣你可以通過seceived對象的屬性並最終看到視圖。喜歡weatherData.forecast.somePropertyHere – Artemis 2014-10-08 09:58:15

回答

1

編輯:我爲你演示了用ng-repeat的用法。這裏是FIDDLE

它必須是這樣的:

<ul> 
    <li ng-repeat="forecast in weatherData.forecast.simpleforecast.forecastday"> 
     <br/>date: {{forecast.date.pretty}} 
     <br/>high: {{forecast.high.celsius}}, 
     <br/>low: {{forecast.low.celsius}} 
    </li> 
</ul> 

我建議使用一些JSON瀏覽器/格式化工具來尋找你從一個複雜的JSON想要的數據。其實我發現它使用that工具。

爲了讓今天的低溫和高溫

data.forecast.simpleforecast.forecastday[0].high.celsius 

data.forecast.simpleforecast.forecastday[0].low.celsius 

而且服務讓4天天氣,如果你想改變他們預測一天的指標。 0是今天,1是明天等等。

+0

我試過你的方法,但似乎不喜歡它 – Indrick 2014-10-08 10:17:48

+0

更正了以攝氏度打印的錯字。還添加了一個工作小提琴來演示ng-repeat的用法。 – 2014-10-08 10:35:31

+0

ahh好吧我知道我做錯了什麼時候測試它我把weatherData.forecast.simpleforecast.forecastday放在{{}} – Indrick 2014-10-08 10:39:32

0
<li ng-repeat="weather in weatherData.forecast.forecast.simpleforecast"> 
    {{weather.forecastday[0].high.celsius}} 
    {{weather.forecastday[0].low.celsius}} 
</li> 
+0

這不工作的原因:( – Indrick 2014-10-08 10:17:20

+0

嘗試{{weather.forecastday [0] .high .celsius}} – 2014-10-08 10:32:16