2016-12-14 81 views
0

我對Angular JS非常新穎,只是想了解基礎知識。我想我有一個分配JSONObject到$ scope.talks的問題。該表現在顯示任何值。與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 | 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"}]} 

您應該指定範圍變量

$scope.talks = talks.talks 

控制器看起來像

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功能必須是這樣的:

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控制檯而不是警報或打印是一種很好的做法。

祝你好運!