2017-06-10 55 views
0

我遇到了使用angularjs從Unsplash API獲取隨機圖像的問題。我曾嘗試使用下面的代碼示例,我發現試過,但它不工作:從使用angularjs的unsplash API獲取隨機圖像

$scope.images = function(){ 
$http({ 
    method: "GET", 
    url: "https://api.unsplash.com/photos/?client_id=1a28e59e586593faf822eb102154d46e8f56c830d3e5d896a0293804233f991a&per_page=30&page="+$scope.pagenumber, 
}).then(
    function(res) 
    { 
     var totalFound=res.data.length; 
     console.log('totalFound',res); 
     var photo=[]; 
     for(var i=0;i<totalFound;i++) 
     { 
      var full=res.data[i].urls.full; 
      var regular=res.data[i].urls.regular; 
      var raw=res.data[i].urls.raw; 
      var small=res.data[i].urls.small; 
      var thumb=res.data[i].urls.thumb; 

      photo.push({ 
       full:full, 
       regular:regular, 
       raw:raw, 
       small:small, 
       thumb:thumb 
      }); 

     } 
     $scope.photo=photo; 

    }, 
    function(res) 
    { 
     console.log('error',res); 
    }); 
    } 
+1

沒有結果?沒有錯誤沒有輸出什麼?你的屏幕只是空白? ...打開顯示器:)你的代碼似乎並不完整,請填寫空格,並檢查你的控制檯。 – shaunhusain

回答

0

您的代碼工作得很好,但你在void function設置的代碼,the void function意味着功能,無需回報。

當您設置的功能的一些代碼,你必須直接調用該函數,在角度你可以從兩側,viewcontroller調用它。

注:這是更好的,如果你在角從視圖中使用angular.forEach代替forarrays

從控制器

$scope.images = function() { 
    //content 
} 

//call the function to have a result 
$scope.images(); 

<div ng-init="images()"> 
    <img ng-src="{{photo.thumb}}" ng-repeat="photo in photos"/> 
</div> 

在線樣本

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

 

 
app.controller("ctrl", ["$scope", "$http", function($scope, $http) { 
 
    $scope.images = function() { 
 
    $http({ 
 
     method: "GET", 
 
     header: { 
 
     'Content-Type': "application/json", 
 
     }, 
 
     url: "https://api.unsplash.com/photos/?client_id=1a28e59e586593faf822eb102154d46e8f56c830d3e5d896a0293804233f991a&per_page=30&page=2", 
 
    }).then(function(res) { 
 
     var totalFound = res.data.length; 
 

 
     var photos = []; 
 

 
     for (var i = 0; i < totalFound; i++) { 
 
      var full = res.data[i].urls.full; 
 
      var regular = res.data[i].urls.regular; 
 
      var raw = res.data[i].urls.raw; 
 
      var small = res.data[i].urls.small; 
 
      var thumb = res.data[i].urls.thumb; 
 

 
      photos.push({ 
 
      full: full, 
 
      regular: regular, 
 
      raw: raw, 
 
      small: small, 
 
      thumb: thumb 
 
      }); 
 
     } 
 

 
     $scope.photos = photos; 
 

 
     }, 
 
     function(res) { 
 
     console.log('error', res); 
 
     }); 
 
    } 
 

 
    $scope.images(); 
 
}]);
img { 
 
    height: 150px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl"> 
 
    <img ng-src="{{photo.thumb}}" ng-repeat="photo in photos" /> 
 
</div>