0

目前,我正在做这样的事情:

var albumList = $resource('https://api.imgur.com/3/account/guy123/albums').get(function () {
    albumList.data.forEach(function (album) {
        albums.push(album);
    });
});

如何将其转换为可以在我的服务和控制器中调用的函数,例如:

factory('Imgur', function($resource, $http) {
    var albumsService = {};
    var albums = [];

    albumsService.getAlbumList = function() {
        var albumList = $resource('https://api.imgur.com/3/account/guy123/albums').get(function () {
            albumList.data.forEach(function (album) {
                albums.push(album);
            });
        });
    };

    albumsService.albumList = function() {
        albumsService.getAlbumList();
        return albums;
    };

    return albumsService;
});


.controller('Filters', ['$scope','Imgur', function($scope, Imgur) {
    $scope.imgur = Imgur;
    $scope.imgur.albumList();
    //OR
    $scope.imgur.getAlbumList();

    //Some good context here is what if a user wanted to "refresh" the data.
    $scope.updateFilter = function() {
        $scope.imgur.getAlbumList();
    }; 


}]);

最终目标是能够根据需要多次调用资源服务。服务应该是服务内部和控制器内部都可以调用的函数。

4

2 回答 2

1
angular.module("MyApp", ['ng-resource']).
  service("Database", function() {
    return {
      albums : $resource('https://api.imgur.com/3/account/guy123/albums')
    }
  }).
  controller("MyCtrl", function(Database) {
    $scope.albums = Database.albums.query();
  })

然后在你的 HTML

<html ng-app="MyApp">
<head></head>
<body ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="album in albums">
      {{album.name}}
    </li>
  </ul>
</body> 
</html>
于 2013-05-06T17:38:21.970 回答
1

服务

var service = angular.module("yourApp.service", ['ngResource']);
service.factory('albumsService', [$resource',function ($resource){
    return $resource('https://api.imgur.com/3/account/guy123/albums',{},{
         query: {method: "GET", isArray:true}
    });
}]);

然后在控制器中

$scope.albumList = albumsService.query();
于 2013-05-06T17:39:46.387 回答