使用angularjs从unsplash api获取随机图像

时间:2017-06-10 23:24:03

标签: javascript angularjs

我遇到使用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 个答案:

答案 0 :(得分:0)

您的代码运行正常,但您在void functionthe void function表示函数中设置代码而不返回。

  

当您在函数中设置一些代码时,您必须直接调用该函数,在角度中,您可以从viewcontroller双方调用它。

     

注意:如果在angular.forEach

的角度中使用for代替arrays,效果要好得多
来自控制器的

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