2017-06-10 10 views
0

Angsを使用してUnsplash APIからランダムな画像を取得する際に問題があります。私は私が見つけた次のコード例を使用して試してみましたが、それは動作していない:angularjsを使用して、アンプラッシュ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、両方の側からそれを呼び出すことができ、直接その関数を呼び出す必要があります。

注:ビューからコントローラ

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

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

からarrays

ための角度でangular.forEach代わりforを使用する場合、それははるかにましだ

<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>

関連する問題