我向服務器請求數據,獲取到的數據竟然不能顯示在頁面上 我那個氣啊.....
<ul>
<!-- <li ng-repeat="phone in phones">
{{phone.name}}
<p>{{phone.snippet}}</p>
</li> -->
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
頁面上綁定了數據
創建服務 HomeExchangeList
.service('HomeExchangeList', function($rootScope, $http, $log) {
this.getHomeExchange = function() {
var rates = $http({
method: 'GET',
url: 'http://www.w3schools.com//website/Customers_JSON.php'
}).success(function(data) {
$log.log(data);
// removed your return data; it doesn't do anything, and this success is only added to log the result. if you don't need the log other than for debugging, get rid of this success handler too.
}); return rates;
};
})
在控制器中 調用數據
.controller('DashCtrl', function($scope, HomeExchangeList) {
HomeExchangeList.getHomeExchange().success(function(data) {
$scope.names = data
});
})
注:
這裏的控制器 注入了HomeExchangeList 服務 ;然後調用服務HomeExchangeList 的getHomeExchange()函數 ,在回調函數.success(function(data){ })裏面綁定數據 只有這樣才能顯示
2. 另外一種
創建服務 phoneService
.factory('phoneService', function($http, $q) {
return {
getPhones: function() {
var deferred = $q.defer();
$http.get('http://www.w3schools.com//website/Customers_JSON.php').success(function(data) {
console.log('success');
deferred.resolve(data);
}).error(function(){
console.log('error');
deferred.reject();
});
return deferred.promise;
}
}
})
創建控制器
.controller('DashCtrl2', function($scope,phoneService) { phoneService.getPhones().then(function(data) {
$scope.names = data;
});
})
注:
服務phoneService 中有promise 的影響 ;所以在控制器中注入phoneService 服務時 ,調用服務的函數 需要 .then(function(data){}) 裏面綁定數據
3. 還有這種
.factory('Recipe',['$resource',function($resource){
return $resource('http://www.w3schools.com//website/Customers_JSON.php');
}])
.factory('loadRecipes',['Recipe','$q',function(Recipe,$q){
return function(){
var defer = $q.defer();
Recipe.query(function(recipes){
defer.resolve(recipes)
},function(){
defer.reject();
});
return defer.promise;
}
}]);
控制器為
.controller('DashCtrl1', function($scope,loadRecipes) { loadRecipes().then(function(data) {
$scope.names = data;
}); })
這種跟第二種一樣的原理......