我向服務器請求數據,獲取到的數據竟然不能顯示在頁面上 我那個氣啊.....
1 <ul> 2 <!-- <li ng-repeat="phone in phones"> 3 {{phone.name}} 4 <p>{{phone.snippet}}</p> 5 </li> --> 6 <li ng-repeat="x in names"> 7 {{ x.Name + ', ' + x.Country }} 8 </li> 9 </ul>
頁面上綁定了數據
創建服務 HomeExchangeList
1 .service('HomeExchangeList', function($rootScope, $http, $log) { 2 this.getHomeExchange = function() { 3 var rates = $http({ 4 method: 'GET', 5 url: 'http://www.w3schools.com//website/Customers_JSON.php' 6 }).success(function(data) { 7 $log.log(data); 8 // 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. 9 }); 10 11 return rates; 12 }; 13 })
在控制器中 調用數據
1 .controller('DashCtrl', function($scope, HomeExchangeList) { 2 HomeExchangeList.getHomeExchange().success(function(data) { 3 $scope.names = data 4 }); 5 })
注:
這裏的控制器 注入了HomeExchangeList 服務 ;然後調用服務HomeExchangeList 的getHomeExchange()函數 ,在回調函數.success(function(data){ })裏面綁定數據 只有這樣才能顯示
2. 另外一種
創建服務 phoneService
1 .factory('phoneService', function($http, $q) { 2 return { 3 getPhones: function() { 4 var deferred = $q.defer(); 5 $http.get('http://www.w3schools.com//website/Customers_JSON.php').success(function(data) { 6 console.log('success'); 7 deferred.resolve(data); 8 }).error(function(){ 9 console.log('error'); 10 deferred.reject(); 11 }); 12 return deferred.promise; 13 } 14 } 15 })
創建控制器
1 .controller('DashCtrl2', function($scope,phoneService) { 2 3 phoneService.getPhones().then(function(data) { 4 $scope.names = data; 5 }); 6 })
注:
服務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; }); })
這種跟第二種一樣的原理......
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步