2016-12-14 6 views
0

私はAngular JSを初めて使っていて、基本を学んでいます。私は$ scope.talksにJSONObjectを割り当てることに問題があると思う。表にはどの値も表示されます。AngularJSを使って簡単なAJAX呼び出しを作成する

ここで私はJSONObjectを取得するために呼び出します

<script type = "text/javascript"> 
var myApp = angular.module('myApp',[]); 
myApp.factory("EventsService", function ($http, $q) { 
return { 
getTalks: function() { 
// Get the deferred object 
var deferred = $q.defer(); 

// Initiates the AJAX call 
$http({ method: 'GET', url: 'http://localhost:8080/greeting' 
}).success(deferred.resolve).error(deferred.reject); 
// Returns the promise - Contains result once request completes 
return deferred.promise; 
} 
} 
}); 
myApp.controller("HelloWorldCtrl", function ($scope, EventsService) 
{ 
EventsService.getTalks().then(function (talks) { 
$scope.talks = talks.data 
}, function() 
{ alert('error while fetching talks from server') }) 
}); 
</script> 

JSONObjectが呼び出しによって返さは以下の通りです:

{"talks":[{"duration":"45","venue":"5","speaker":"bill gates","name":"test","id":"45"},{"duration":"45","venue":"2","speaker":"bill gates","name":"another test","id":"33"}]} 

そして、ここでデータをレンダリングするためのコードです:

<body ng-app="myApp" ng-controller = "HelloWorldCtrl" style="font-family: Verdana, Geneva, 'DejaVu Sans', sans-serif"> 
<table class ="table table-condensed table-hover"> 
<tr> 
<th>Id</th> 
<th>Name</th> 
<th>Speaker</th> 
<th>Venue</th> 
<th>Duration</th> 
</tr> 
<tr ng-repeat = "talk in talks"> 
<td>{{talk.id}}</td> 
<td>{{talk.name}}</td> 
<td>{{talk.speaker}}</td> 
<td>{{talk.venue}}</td> 
<td>{{talk.duration}}</td> 
</tr> 
</table> 
</body> 
+1

問題は何ですか? – Deep

+0

テーブルに値が表示されないため、スコープ変数が正しく定義されていないと思います。 –

+0

'talks'オブジェクトを印刷すると、何が表示されますか?それを見るには '

{{ talks | json }}
'を使ってください。 –

答えて

1

レスポンスオブジェクトにtalks.dataプロパティはありません。

{"talks":[{"duration":"45","venue":"5","speaker":"bill gates","name":"test","id":"45"},{"duration":"45","venue":"2","speaker":"bill gates","name":"another test","id":"33"}]} 

あなたは、コントローラは、

myApp.controller("HelloWorldCtrl", function ($scope, EventsService) 
{ 
EventsService.getTalks().then(function (talks) { 
$scope.talks = talks.talks 
}, function() 
{ alert('error while fetching talks from server') }) 
}); 
0

getTalksようになります機能のようなものでなければならない

$scope.talks = talks.talks 

としてスコープ変数を割り当てる必要があります。

getTalks: function() { 
    return $http.get('http://localhost:8080/greeting'); 
} 

アンギュラ方法$httpは約束を返すでしょう。あなたのコードでは、の内側にという約束を返します。私のコードはそれを修正し、それをよりきれいにする。

次に、あなたのコントローラで、入れ:

myApp.controller("HelloWorldCtrl", function ($scope, EventsService) { 
    $scope.talks = EventsService.getTalks().then(
     function(res) { 
      return res.data; 
     }, 
     function(err) { 
      console.log("An error has ocurred!", err); 
     } 
    ) 
}); 

をあなたが約束を解決しているthen()を使用します。コードでアラートやプリントの代わりにJavaScriptコンソールを使用することをお勧めします。

幸運を祈る!

関連する問題